WaterProxy.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. /*
  2. * WaterProxy.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 "WaterProxy.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/CMap.h"
  18. #include "../../mapping/CMapEditManager.h"
  19. #include "../RmgPath.h"
  20. #include "../RmgObject.h"
  21. #include "ObjectManager.h"
  22. #include "../Functions.h"
  23. #include "RoadPlacer.h"
  24. #include "TreasurePlacer.h"
  25. #include "TownPlacer.h"
  26. #include "ConnectionsPlacer.h"
  27. #include "../TileInfo.h"
  28. #include "WaterAdopter.h"
  29. #include "../RmgArea.h"
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. void WaterProxy::process()
  32. {
  33. for(const auto & t : zone.area().getTilesVector())
  34. {
  35. map.setZoneID(t, zone.getId());
  36. map.setOccupied(t, ETileType::POSSIBLE);
  37. }
  38. auto v = zone.getArea().getTilesVector();
  39. mapProxy->drawTerrain(zone.getRand(), v, zone.getTerrainType());
  40. //check terrain type
  41. for([[maybe_unused]] const auto & t : zone.area().getTilesVector())
  42. {
  43. assert(map.isOnMap(t));
  44. assert(map.getTile(t).terType->getId() == zone.getTerrainType());
  45. }
  46. for(const auto & z : map.getZones())
  47. {
  48. if(z.second->getId() == zone.getId())
  49. continue;
  50. Zone::Lock lock(z.second->areaMutex);
  51. for(const auto & t : z.second->area().getTilesVector())
  52. {
  53. if(map.getTile(t).terType->getId() == zone.getTerrainType())
  54. {
  55. z.second->areaPossible().erase(t);
  56. z.second->area().erase(t);
  57. zone.area().add(t);
  58. zone.areaPossible().add(t);
  59. map.setZoneID(t, zone.getId());
  60. map.setOccupied(t, ETileType::POSSIBLE);
  61. }
  62. }
  63. }
  64. if(!zone.area().contains(zone.getPos()))
  65. {
  66. zone.setPos(zone.area().getTilesVector().front());
  67. }
  68. zone.initFreeTiles();
  69. collectLakes();
  70. }
  71. void WaterProxy::init()
  72. {
  73. for(auto & z : map.getZones())
  74. {
  75. if (!zone.isUnderground())
  76. {
  77. dependency(z.second->getModificator<TownPlacer>());
  78. dependency(z.second->getModificator<WaterAdopter>());
  79. }
  80. postfunction(z.second->getModificator<ConnectionsPlacer>());
  81. postfunction(z.second->getModificator<ObjectManager>());
  82. }
  83. POSTFUNCTION(TreasurePlacer);
  84. }
  85. const std::vector<WaterProxy::Lake> & WaterProxy::getLakes() const
  86. {
  87. RecursiveLock lock(externalAccessMutex);
  88. return lakes;
  89. }
  90. void WaterProxy::collectLakes()
  91. {
  92. RecursiveLock lock(externalAccessMutex);
  93. int lakeId = 0;
  94. for(const auto & lake : connectedAreas(zone.getArea(), true))
  95. {
  96. lakes.push_back(Lake{});
  97. lakes.back().area = lake;
  98. lakes.back().distanceMap = lake.computeDistanceMap(lakes.back().reverseDistanceMap);
  99. for(const auto & t : lake.getBorderOutside())
  100. if(map.isOnMap(t))
  101. lakes.back().neighbourZones[map.getZoneID(t)].add(t);
  102. for(const auto & t : lake.getTiles())
  103. lakeMap[t] = lakeId;
  104. //each lake must have at least one free tile
  105. if(!lake.overlap(zone.freePaths()))
  106. zone.freePaths().add(*lakes.back().reverseDistanceMap[lakes.back().reverseDistanceMap.size() - 1].begin());
  107. ++lakeId;
  108. }
  109. }
  110. RouteInfo WaterProxy::waterRoute(Zone & dst)
  111. {
  112. RouteInfo result;
  113. auto * adopter = dst.getModificator<WaterAdopter>();
  114. if(!adopter)
  115. return result;
  116. if(adopter->getCoastTiles().empty())
  117. return result;
  118. //block zones are not connected by template
  119. for(auto& lake : lakes)
  120. {
  121. if(lake.neighbourZones.count(dst.getId()))
  122. {
  123. if(!lake.keepConnections.count(dst.getId()))
  124. {
  125. for(const auto & ct : lake.neighbourZones[dst.getId()].getTiles())
  126. {
  127. if(map.isPossible(ct))
  128. map.setOccupied(ct, ETileType::BLOCKED);
  129. }
  130. Zone::Lock lock(dst.areaMutex);
  131. dst.areaPossible().subtract(lake.neighbourZones[dst.getId()]);
  132. continue;
  133. }
  134. //Don't place shipyard or boats on the very small lake
  135. if (lake.area.getTiles().size() < 25)
  136. {
  137. logGlobal->info("Skipping very small lake at zone %d", dst.getId());
  138. continue;
  139. }
  140. int zoneTowns = 0;
  141. if(auto * m = dst.getModificator<TownPlacer>())
  142. zoneTowns = m->getTotalTowns();
  143. if(dst.getType() == ETemplateZoneType::PLAYER_START || dst.getType() == ETemplateZoneType::CPU_START || zoneTowns)
  144. {
  145. if(placeShipyard(dst, lake, generator.getConfig().shipyardGuard, result))
  146. {
  147. logGlobal->info("Shipyard successfully placed at zone %d", dst.getId());
  148. }
  149. else
  150. {
  151. logGlobal->warn("Shipyard placement failed, trying boat at zone %d", dst.getId());
  152. if(placeBoat(dst, lake, result))
  153. {
  154. logGlobal->warn("Boat successfully placed at zone %d", dst.getId());
  155. }
  156. else
  157. {
  158. logGlobal->error("Boat placement failed at zone %d", dst.getId());
  159. }
  160. }
  161. }
  162. else
  163. {
  164. if(placeBoat(dst, lake, result))
  165. {
  166. logGlobal->info("Boat successfully placed at zone %d", dst.getId());
  167. }
  168. else
  169. {
  170. logGlobal->error("Boat placement failed at zone %d", dst.getId());
  171. }
  172. }
  173. }
  174. }
  175. return result;
  176. }
  177. bool WaterProxy::waterKeepConnection(TRmgTemplateZoneId zoneA, TRmgTemplateZoneId zoneB)
  178. {
  179. for(auto & lake : lakes)
  180. {
  181. if(lake.neighbourZones.count(zoneA) && lake.neighbourZones.count(zoneB))
  182. {
  183. lake.keepConnections.insert(zoneA);
  184. lake.keepConnections.insert(zoneB);
  185. return true;
  186. }
  187. }
  188. return false;
  189. }
  190. bool WaterProxy::placeBoat(Zone & land, const Lake & lake, RouteInfo & info)
  191. {
  192. auto * manager = zone.getModificator<ObjectManager>();
  193. if(!manager)
  194. return false;
  195. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::BOAT);
  196. std::set<si32> sailingBoatTypes; //RMG shall place only sailing boats on water
  197. for(auto subObj : subObjects)
  198. {
  199. //making a temporary object
  200. std::unique_ptr<CGObjectInstance> obj(VLC->objtypeh->getHandlerFor(Obj::BOAT, subObj)->create());
  201. if(auto * testBoat = dynamic_cast<CGBoat *>(obj.get()))
  202. {
  203. if(testBoat->layer == EPathfindingLayer::SAIL)
  204. sailingBoatTypes.insert(subObj);
  205. }
  206. }
  207. if(sailingBoatTypes.empty())
  208. return false;
  209. auto * boat = dynamic_cast<CGBoat *>(VLC->objtypeh->getHandlerFor(Obj::BOAT, *RandomGeneratorUtil::nextItem(sailingBoatTypes, zone.getRand()))->create());
  210. rmg::Object rmgObject(*boat);
  211. rmgObject.setTemplate(zone.getTerrainType());
  212. auto waterAvailable = zone.areaPossible() + zone.freePaths();
  213. rmg::Area coast = lake.neighbourZones.at(land.getId()); //having land tiles
  214. coast.intersect(land.areaPossible() + land.freePaths()); //having only available land tiles
  215. auto boardingPositions = coast.getSubarea([&waterAvailable, this](const int3 & tile) //tiles where boarding is possible
  216. {
  217. //We don't want place boat right to any land object, especiallly the zone guard
  218. if (map.getTileInfo(tile).getNearestObjectDistance() <= 3)
  219. return false;
  220. rmg::Area a({tile});
  221. a = a.getBorderOutside();
  222. a.intersect(waterAvailable);
  223. return !a.empty();
  224. });
  225. while(!boardingPositions.empty())
  226. {
  227. auto boardingPosition = *boardingPositions.getTiles().begin();
  228. rmg::Area shipPositions({boardingPosition});
  229. auto boutside = shipPositions.getBorderOutside();
  230. shipPositions.assign(boutside);
  231. shipPositions.intersect(waterAvailable);
  232. if(shipPositions.empty())
  233. {
  234. boardingPositions.erase(boardingPosition);
  235. continue;
  236. }
  237. //try to place boat at water, create paths on water and land
  238. auto path = manager->placeAndConnectObject(shipPositions, rmgObject, 4, false, true, ObjectManager::OptimizeType::NONE);
  239. auto landPath = land.searchPath(boardingPosition, false);
  240. if(!path.valid() || !landPath.valid())
  241. {
  242. boardingPositions.erase(boardingPosition);
  243. continue;
  244. }
  245. info.blocked = rmgObject.getArea();
  246. info.visitable = rmgObject.getVisitablePosition();
  247. info.boarding = boardingPosition;
  248. info.water = shipPositions;
  249. zone.connectPath(path);
  250. land.connectPath(landPath);
  251. manager->placeObject(rmgObject, false, true);
  252. land.getModificator<ObjectManager>()->updateDistances(rmgObject); //Keep land objects away from the boat
  253. break;
  254. }
  255. return !boardingPositions.empty();
  256. }
  257. bool WaterProxy::placeShipyard(Zone & land, const Lake & lake, si32 guard, RouteInfo & info)
  258. {
  259. auto * manager = land.getModificator<ObjectManager>();
  260. if(!manager)
  261. return false;
  262. int subtype = chooseRandomAppearance(zone.getRand(), Obj::SHIPYARD, land.getTerrainType());
  263. auto * shipyard = dynamic_cast<CGShipyard *>(VLC->objtypeh->getHandlerFor(Obj::SHIPYARD, subtype)->create());
  264. shipyard->tempOwner = PlayerColor::NEUTRAL;
  265. rmg::Object rmgObject(*shipyard);
  266. rmgObject.setTemplate(land.getTerrainType());
  267. bool guarded = manager->addGuard(rmgObject, guard);
  268. auto waterAvailable = zone.areaPossible() + zone.freePaths();
  269. waterAvailable.intersect(lake.area);
  270. rmg::Area coast = lake.neighbourZones.at(land.getId()); //having land tiles
  271. coast.intersect(land.areaPossible() + land.freePaths()); //having only available land tiles
  272. auto boardingPositions = coast.getSubarea([&waterAvailable](const int3 & tile) //tiles where boarding is possible
  273. {
  274. rmg::Area a({tile});
  275. a = a.getBorderOutside();
  276. a.intersect(waterAvailable);
  277. return !a.empty();
  278. });
  279. while(!boardingPositions.empty())
  280. {
  281. auto boardingPosition = *boardingPositions.getTiles().begin();
  282. rmg::Area shipPositions({boardingPosition});
  283. auto boutside = shipPositions.getBorderOutside();
  284. shipPositions.assign(boutside);
  285. shipPositions.intersect(waterAvailable);
  286. if(shipPositions.empty())
  287. {
  288. boardingPositions.erase(boardingPosition);
  289. continue;
  290. }
  291. //try to place shipyard close to boarding position and appropriate water access
  292. auto path = manager->placeAndConnectObject(land.areaPossible(), rmgObject, [&rmgObject, &shipPositions, &boardingPosition](const int3 & tile)
  293. {
  294. //Must only check the border of shipyard and not the added guard
  295. rmg::Area shipyardOut = rmgObject.instances().front()->getBlockedArea().getBorderOutside();
  296. if(!shipyardOut.contains(boardingPosition) || (shipyardOut * shipPositions).empty())
  297. return -1.f;
  298. return 1.0f;
  299. }, guarded, true, ObjectManager::OptimizeType::NONE);
  300. //search path to boarding position
  301. auto searchArea = land.areaPossible() - rmgObject.getArea();
  302. rmg::Path pathToBoarding(searchArea);
  303. pathToBoarding.connect(land.freePaths());
  304. pathToBoarding.connect(path);
  305. pathToBoarding = pathToBoarding.search(boardingPosition, false);
  306. //make sure shipyard places ship at position we defined
  307. rmg::Area shipyardOutToBlock(rmgObject.getArea().getBorderOutside());
  308. shipyardOutToBlock.intersect(waterAvailable);
  309. shipyardOutToBlock.subtract(shipPositions);
  310. shipPositions.subtract(shipyardOutToBlock);
  311. auto pathToBoat = zone.searchPath(shipPositions, true);
  312. if(!path.valid() || !pathToBoarding.valid() || !pathToBoat.valid())
  313. {
  314. boardingPositions.erase(boardingPosition);
  315. continue;
  316. }
  317. land.connectPath(path);
  318. land.connectPath(pathToBoarding);
  319. zone.connectPath(pathToBoat);
  320. info.blocked = rmgObject.getArea();
  321. info.visitable = rmgObject.getVisitablePosition();
  322. info.boarding = boardingPosition;
  323. info.water = shipPositions;
  324. manager->placeObject(rmgObject, guarded, true);
  325. zone.areaPossible().subtract(shipyardOutToBlock);
  326. for(const auto & i : shipyardOutToBlock.getTilesVector())
  327. if(map.isOnMap(i) && map.isPossible(i))
  328. map.setOccupied(i, ETileType::BLOCKED);
  329. break;
  330. }
  331. return !boardingPositions.empty();
  332. }
  333. char WaterProxy::dump(const int3 & t)
  334. {
  335. auto lakeIter = lakeMap.find(t);
  336. if(lakeIter == lakeMap.end())
  337. return '?';
  338. Lake & lake = lakes[lakeMap.at(t)];
  339. for(const auto & i : lake.neighbourZones)
  340. {
  341. if(i.second.contains(t))
  342. return lake.keepConnections.count(i.first) ? std::to_string(i.first)[0] : '=';
  343. }
  344. return '~';
  345. }
  346. VCMI_LIB_NAMESPACE_END