ObjectManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * ObjectManager.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 "ObjectManager.h"
  12. #include "CMapGenerator.h"
  13. #include "TileInfo.h"
  14. #include "RmgMap.h"
  15. #include "RoadPlacer.h"
  16. #include "RiverPlacer.h"
  17. #include "WaterAdopter.h"
  18. #include "../CCreatureHandler.h"
  19. #include "../mapObjects/CommonConstructors.h"
  20. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  21. #include "../mapping/CMap.h"
  22. #include "../mapping/CMapEditManager.h"
  23. #include "Functions.h"
  24. #include "RmgObject.h"
  25. void ObjectManager::process()
  26. {
  27. zone.fractalize();
  28. createRequiredObjects();
  29. }
  30. void ObjectManager::init()
  31. {
  32. DEPENDENCY(WaterAdopter);
  33. POSTFUNCTION(RoadPlacer);
  34. }
  35. void ObjectManager::addRequiredObject(CGObjectInstance * obj, si32 strength)
  36. {
  37. requiredObjects.push_back(std::make_pair(obj, strength));
  38. }
  39. void ObjectManager::addCloseObject(CGObjectInstance * obj, si32 strength)
  40. {
  41. closeObjects.push_back(std::make_pair(obj, strength));
  42. }
  43. void ObjectManager::addNearbyObject(CGObjectInstance * obj, CGObjectInstance * nearbyTarget)
  44. {
  45. nearbyObjects.push_back(std::make_pair(obj, nearbyTarget));
  46. }
  47. void ObjectManager::updateDistances(const rmg::Object & obj)
  48. {
  49. for (auto tile : zone.areaPossible().getTiles()) //don't need to mark distance for not possible tiles
  50. {
  51. ui32 d = obj.getArea().distanceSqr(tile); //optimization, only relative distance is interesting
  52. map.setNearestObjectDistance(tile, std::min((float)d, map.getNearestObjectDistance(tile)));
  53. }
  54. }
  55. const rmg::Area & ObjectManager::getVisitableArea() const
  56. {
  57. return objectsVisitableArea;
  58. }
  59. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, std::function<float(const int3)> weightFunction, bool optimizer) const
  60. {
  61. float bestWeight = 0.f;
  62. int3 result(-1, -1, -1);
  63. for(const auto & tile : searchArea.getTiles())
  64. {
  65. obj.setPosition(tile);
  66. if(!searchArea.contains(obj.getArea()) || !searchArea.overlap(obj.getAccessibleArea()))
  67. continue;
  68. float weight = weightFunction(tile);
  69. if(weight > bestWeight)
  70. {
  71. bestWeight = weight;
  72. result = tile;
  73. if(!optimizer)
  74. break;
  75. }
  76. }
  77. if(result.valid())
  78. obj.setPosition(result);
  79. return result;
  80. }
  81. int3 ObjectManager::findPlaceForObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, bool optimizer) const
  82. {
  83. return findPlaceForObject(searchArea, obj, [this, min_dist](const int3 & tile)
  84. {
  85. auto ti = map.getTile(tile);
  86. float dist = ti.getNearestObjectDistance();
  87. if(dist < min_dist)
  88. return -1.f;
  89. return dist;
  90. }, optimizer);
  91. }
  92. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, si32 min_dist, bool isGuarded, bool onlyStraight, bool optimizer) const
  93. {
  94. return placeAndConnectObject(searchArea, obj, [this, min_dist](const int3 & tile)
  95. {
  96. auto ti = map.getTile(tile);
  97. float dist = ti.getNearestObjectDistance();
  98. if(dist < min_dist)
  99. return -1.f;
  100. return dist;
  101. }, isGuarded, onlyStraight, optimizer);
  102. }
  103. rmg::Path ObjectManager::placeAndConnectObject(const rmg::Area & searchArea, rmg::Object & obj, std::function<float(const int3)> weightFunction, bool isGuarded, bool onlyStraight, bool optimizer) const
  104. {
  105. int3 pos;
  106. auto possibleArea = searchArea;
  107. while(true)
  108. {
  109. pos = findPlaceForObject(possibleArea, obj, weightFunction, optimizer);
  110. if(!pos.valid())
  111. {
  112. return rmg::Path::invalid();
  113. }
  114. possibleArea.erase(pos); //do not place again at this point
  115. auto accessibleArea = obj.getAccessibleArea(isGuarded) * (zone.areaPossible() + zone.freePaths());
  116. //we should exclude tiles which will be covered
  117. if(isGuarded)
  118. {
  119. auto & guardedArea = obj.instances().back()->getAccessibleArea();
  120. accessibleArea.intersect(guardedArea);
  121. }
  122. auto path = zone.searchPath(accessibleArea, onlyStraight, [&obj, isGuarded](const int3 & t)
  123. {
  124. if(isGuarded)
  125. {
  126. auto & guardedArea = obj.instances().back()->getAccessibleArea();
  127. auto & unguardedArea = obj.getAccessibleArea(isGuarded);
  128. if(unguardedArea.contains(t) && !guardedArea.contains(t))
  129. return false;
  130. }
  131. return !obj.getArea().contains(t);
  132. });
  133. if(path.valid())
  134. {
  135. return path;
  136. }
  137. }
  138. }
  139. bool ObjectManager::createRequiredObjects()
  140. {
  141. logGlobal->trace("Creating required objects");
  142. for(const auto & object : requiredObjects)
  143. {
  144. auto * obj = object.first;
  145. int3 pos;
  146. rmg::Object rmgObject(*obj);
  147. rmgObject.setTemplate(zone.getTerrainType());
  148. bool guarded = addGuard(rmgObject, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY));
  149. auto path = placeAndConnectObject(zone.areaPossible(), rmgObject, 3, guarded, false, true);
  150. if(!path.valid())
  151. {
  152. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  153. return false;
  154. }
  155. zone.connectPath(path);
  156. placeObject(rmgObject, guarded, true);
  157. for(const auto & nearby : nearbyObjects)
  158. {
  159. if(nearby.second != obj)
  160. continue;
  161. rmg::Object rmgNearObject(*nearby.first);
  162. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  163. possibleArea.intersect(zone.areaPossible());
  164. if(possibleArea.empty())
  165. {
  166. rmgNearObject.clear();
  167. continue;
  168. }
  169. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), generator.rand));
  170. placeObject(rmgNearObject, false, false);
  171. }
  172. }
  173. for(const auto & object : closeObjects)
  174. {
  175. auto * obj = object.first;
  176. int3 pos;
  177. auto possibleArea = zone.areaPossible();
  178. rmg::Object rmgObject(*obj);
  179. rmgObject.setTemplate(zone.getTerrainType());
  180. bool guarded = addGuard(rmgObject, object.second, (obj->ID == Obj::MONOLITH_TWO_WAY));
  181. auto path = placeAndConnectObject(zone.areaPossible(), rmgObject,
  182. [this, &rmgObject](const int3 & tile)
  183. {
  184. float dist = rmgObject.getArea().distanceSqr(zone.getPos());
  185. dist *= (dist > 12.f * 12.f) ? 10.f : 1.f; //tiles closer 12 are preferrable
  186. dist = 1000000.f - dist; //some big number
  187. return dist + map.getNearestObjectDistance(tile);
  188. }, guarded, false, true);
  189. if(!path.valid())
  190. {
  191. logGlobal->error("Failed to fill zone %d due to lack of space", zone.getId());
  192. return false;
  193. }
  194. zone.connectPath(path);
  195. placeObject(rmgObject, guarded, true);
  196. for(const auto & nearby : nearbyObjects)
  197. {
  198. if(nearby.second != obj)
  199. continue;
  200. rmg::Object rmgNearObject(*nearby.first);
  201. rmg::Area possibleArea(rmgObject.instances().front()->getBlockedArea().getBorderOutside());
  202. possibleArea.intersect(zone.areaPossible());
  203. if(possibleArea.empty())
  204. {
  205. rmgNearObject.clear();
  206. continue;
  207. }
  208. rmgNearObject.setPosition(*RandomGeneratorUtil::nextItem(possibleArea.getTiles(), generator.rand));
  209. placeObject(rmgNearObject, false, false);
  210. }
  211. }
  212. //create object on specific positions
  213. //TODO: implement guards
  214. for (const auto &obj : instantObjects)
  215. {
  216. rmg::Object rmgObject(*obj.first);
  217. rmgObject.setPosition(obj.second);
  218. placeObject(rmgObject, false, false);
  219. }
  220. requiredObjects.clear();
  221. closeObjects.clear();
  222. nearbyObjects.clear();
  223. instantObjects.clear();
  224. return true;
  225. }
  226. void ObjectManager::placeObject(rmg::Object & object, bool guarded, bool updateDistance)
  227. {
  228. object.finalize(map);
  229. zone.areaPossible().subtract(object.getArea());
  230. bool keepVisitable = zone.freePaths().contains(object.getVisitablePosition());
  231. zone.freePaths().subtract(object.getArea()); //just to avoid areas overlapping
  232. if(keepVisitable)
  233. zone.freePaths().add(object.getVisitablePosition());
  234. zone.areaUsed().unite(object.getArea());
  235. zone.areaUsed().erase(object.getVisitablePosition());
  236. if(guarded)
  237. {
  238. auto guardedArea = object.instances().back()->getAccessibleArea();
  239. guardedArea.add(object.instances().back()->getVisitablePosition());
  240. auto areaToBlock = object.getAccessibleArea(true);
  241. areaToBlock.subtract(guardedArea);
  242. zone.areaPossible().subtract(areaToBlock);
  243. for(auto & i : areaToBlock.getTilesVector())
  244. if(map.isOnMap(i) && map.isPossible(i))
  245. map.setOccupied(i, ETileType::BLOCKED);
  246. }
  247. if(updateDistance)
  248. updateDistances(object);
  249. for(auto * instance : object.instances())
  250. {
  251. objectsVisitableArea.add(instance->getVisitablePosition());
  252. objects.push_back(&instance->object());
  253. if(auto * m = zone.getModificator<RoadPlacer>())
  254. {
  255. if(instance->object().appearance.isVisitableFromTop())
  256. m->areaForRoads().add(instance->getVisitablePosition());
  257. else
  258. {
  259. m->areaIsolated().add(instance->getVisitablePosition() + int3(0, -1, 0));
  260. }
  261. }
  262. }
  263. switch(object.instances().front()->object().ID)
  264. {
  265. case Obj::TOWN:
  266. case Obj::RANDOM_TOWN:
  267. case Obj::MONOLITH_TWO_WAY:
  268. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  269. case Obj::MONOLITH_ONE_WAY_EXIT:
  270. case Obj::SUBTERRANEAN_GATE:
  271. case Obj::SHIPYARD:
  272. if(auto * m = zone.getModificator<RoadPlacer>())
  273. m->addRoadNode(object.instances().front()->getVisitablePosition());
  274. break;
  275. case Obj::WATER_WHEEL:
  276. if(auto * m = zone.getModificator<RiverPlacer>())
  277. m->addRiverNode(object.instances().front()->getVisitablePosition());
  278. break;
  279. default:
  280. break;
  281. }
  282. }
  283. CGCreature * ObjectManager::chooseGuard(si32 strength, bool zoneGuard)
  284. {
  285. //precalculate actual (randomized) monster strength based on this post
  286. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  287. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  288. int monsterStrength = (zoneGuard ? 0 : zone.zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  289. static const std::array<int, 5> value1{2500, 1500, 1000, 500, 0};
  290. static const std::array<int, 5> value2{7500, 7500, 7500, 5000, 5000};
  291. static const std::array<float, 5> multiplier1{0.5, 0.75, 1.0, 1.5, 1.5};
  292. static const std::array<float, 5> multiplier2{0.5, 0.75, 1.0, 1.0, 1.5};
  293. int strength1 = static_cast<int>(std::max(0.f, (strength - value1.at(monsterStrength)) * multiplier1.at(monsterStrength)));
  294. int strength2 = static_cast<int>(std::max(0.f, (strength - value2.at(monsterStrength)) * multiplier2.at(monsterStrength)));
  295. strength = strength1 + strength2;
  296. if (strength < generator.getConfig().minGuardStrength)
  297. return nullptr; //no guard at all
  298. CreatureID creId = CreatureID::NONE;
  299. int amount = 0;
  300. std::vector<CreatureID> possibleCreatures;
  301. for(auto cre : VLC->creh->objects)
  302. {
  303. if(cre->special)
  304. continue;
  305. if(!cre->AIValue) //bug #2681
  306. continue;
  307. if(!vstd::contains(zone.getMonsterTypes(), cre->faction))
  308. continue;
  309. if(((si32)(cre->AIValue * (cre->ammMin + cre->ammMax) / 2) < strength) && (strength < (si32)cre->AIValue * 100)) //at least one full monster. size between average size of given stack and 100
  310. {
  311. possibleCreatures.push_back(cre->idNumber);
  312. }
  313. }
  314. if(possibleCreatures.size())
  315. {
  316. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, generator.rand);
  317. amount = strength / VLC->creh->objects[creId]->AIValue;
  318. if (amount >= 4)
  319. amount = static_cast<int>(amount * generator.rand.nextDouble(0.75, 1.25));
  320. }
  321. else //just pick any available creature
  322. {
  323. creId = CreatureID(132); //Azure Dragon
  324. amount = strength / VLC->creh->objects[creId]->AIValue;
  325. }
  326. auto guardFactory = VLC->objtypeh->getHandlerFor(Obj::MONSTER, creId);
  327. auto guard = (CGCreature *) guardFactory->create(ObjectTemplate());
  328. guard->character = CGCreature::HOSTILE;
  329. auto hlp = new CStackInstance(creId, amount);
  330. //will be set during initialization
  331. guard->putStack(SlotID(0), hlp);
  332. return guard;
  333. }
  334. bool ObjectManager::addGuard(rmg::Object & object, si32 strength, bool zoneGuard)
  335. {
  336. auto * guard = chooseGuard(strength, zoneGuard);
  337. if(!guard)
  338. return false;
  339. rmg::Area visitablePos({object.getVisitablePosition()});
  340. visitablePos.unite(visitablePos.getBorderOutside());
  341. auto accessibleArea = object.getAccessibleArea();
  342. accessibleArea.intersect(visitablePos);
  343. if(accessibleArea.empty())
  344. {
  345. delete guard;
  346. return false;
  347. }
  348. auto guardTiles = accessibleArea.getTilesVector();
  349. auto guardPos = *std::min_element(guardTiles.begin(), guardTiles.end(), [&object](const int3 & l, const int3 & r)
  350. {
  351. auto p = object.getVisitablePosition();
  352. if(l.y > r.y)
  353. return true;
  354. if(l.y == r.y)
  355. return abs(l.x - p.x) < abs(r.x - p.x);
  356. return false;
  357. });
  358. auto & instance = object.addInstance(*guard);
  359. instance.setPosition(guardPos - object.getPosition());
  360. return true;
  361. }