CObjectHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*
  2. * CObjectHandler.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 "CObjectHandler.h"
  12. #include "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CHeroHandler.h"
  15. #include "../CSoundBase.h"
  16. #include "../filesystem/ResourceID.h"
  17. #include "../IGameCallback.h"
  18. #include "../CGameState.h"
  19. #include "../StringConstants.h"
  20. #include "../mapping/CMap.h"
  21. #include "../TerrainHandler.h"
  22. #include "CObjectClassesHandler.h"
  23. #include "CGTownInstance.h"
  24. #include "../serializer/JsonSerializeFormat.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. IGameCallback * IObjectInterface::cb = nullptr;
  27. ///helpers
  28. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  29. {
  30. OpenWindow ow;
  31. ow.window = type;
  32. ow.id1 = id1;
  33. ow.id2 = id2;
  34. IObjectInterface::cb->sendAndApply(&ow);
  35. }
  36. static void showInfoDialog(const PlayerColor & playerID, const ui32 txtID, const ui16 soundID)
  37. {
  38. InfoWindow iw;
  39. iw.soundID = soundID;
  40. iw.player = playerID;
  41. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  42. IObjectInterface::cb->sendAndApply(&iw);
  43. }
  44. /*static void showInfoDialog(const ObjectInstanceID heroID, const ui32 txtID, const ui16 soundID)
  45. {
  46. const PlayerColor playerID = IObjectInterface::cb->getOwner(heroID);
  47. showInfoDialog(playerID,txtID,soundID);
  48. }*/
  49. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID = 0)
  50. {
  51. const PlayerColor playerID = h->getOwner();
  52. showInfoDialog(playerID,txtID,soundID);
  53. }
  54. ///IObjectInterface
  55. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  56. {}
  57. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  58. {}
  59. void IObjectInterface::newTurn(CRandomGenerator & rand) const
  60. {}
  61. void IObjectInterface::initObj(CRandomGenerator & rand)
  62. {}
  63. void IObjectInterface::setProperty( ui8 what, ui32 val )
  64. {}
  65. bool IObjectInterface::wasVisited (PlayerColor player) const
  66. {
  67. return false;
  68. }
  69. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  70. {
  71. return false;
  72. }
  73. void IObjectInterface::postInit()
  74. {}
  75. void IObjectInterface::preInit()
  76. {}
  77. void IObjectInterface::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  78. {}
  79. void IObjectInterface::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  80. {}
  81. void IObjectInterface::garrisonDialogClosed(const CGHeroInstance *hero) const
  82. {}
  83. void IObjectInterface::heroLevelUpDone(const CGHeroInstance *hero) const
  84. {}
  85. CObjectHandler::CObjectHandler()
  86. {
  87. logGlobal->trace("\t\tReading resources prices ");
  88. const JsonNode config2(ResourceID("config/resources.json"));
  89. for(const JsonNode &price : config2["resources_prices"].Vector())
  90. {
  91. resVals.push_back(static_cast<ui32>(price.Float()));
  92. }
  93. logGlobal->trace("\t\tDone loading resource prices!");
  94. }
  95. //TODO: remove constructor
  96. CGObjectInstance::CGObjectInstance():
  97. pos(-1,-1,-1),
  98. ID(Obj::NO_OBJ),
  99. subID(-1),
  100. tempOwner(PlayerColor::UNFLAGGABLE),
  101. blockVisit(false)
  102. {
  103. }
  104. //must be instantiated in .cpp file for access to complete types of all member fields
  105. CGObjectInstance::~CGObjectInstance() = default;
  106. int32_t CGObjectInstance::getObjGroupIndex() const
  107. {
  108. return ID.num;
  109. }
  110. int32_t CGObjectInstance::getObjTypeIndex() const
  111. {
  112. return subID;
  113. }
  114. int3 CGObjectInstance::getPosition() const
  115. {
  116. return pos;
  117. }
  118. void CGObjectInstance::setOwner(const PlayerColor & ow)
  119. {
  120. tempOwner = ow;
  121. }
  122. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  123. {
  124. return appearance->getWidth();
  125. }
  126. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  127. {
  128. return appearance->getHeight();
  129. }
  130. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  131. {
  132. return appearance->isVisitableAt(pos.x - x, pos.y - y);
  133. }
  134. bool CGObjectInstance::blockingAt(int x, int y) const
  135. {
  136. return appearance->isBlockedAt(pos.x - x, pos.y - y);
  137. }
  138. bool CGObjectInstance::coveringAt(int x, int y) const
  139. {
  140. return appearance->isVisibleAt(pos.x - x, pos.y - y);
  141. }
  142. std::set<int3> CGObjectInstance::getBlockedPos() const
  143. {
  144. std::set<int3> ret;
  145. for(int w=0; w<getWidth(); ++w)
  146. {
  147. for(int h=0; h<getHeight(); ++h)
  148. {
  149. if(appearance->isBlockedAt(w, h))
  150. ret.insert(int3(pos.x - w, pos.y - h, pos.z));
  151. }
  152. }
  153. return ret;
  154. }
  155. std::set<int3> CGObjectInstance::getBlockedOffsets() const
  156. {
  157. return appearance->getBlockedOffsets();
  158. }
  159. void CGObjectInstance::setType(si32 ID, si32 subID)
  160. {
  161. auto position = visitablePos();
  162. auto oldOffset = getVisitableOffset();
  163. auto &tile = cb->gameState()->map->getTile(position);
  164. //recalculate blockvis tiles - new appearance might have different blockmap than before
  165. cb->gameState()->map->removeBlockVisTiles(this, true);
  166. auto handler = VLC->objtypeh->getHandlerFor(ID, subID);
  167. if(!handler)
  168. {
  169. logGlobal->error("Unknown object type %d:%d at %s", ID, subID, visitablePos().toString());
  170. return;
  171. }
  172. if(!handler->getTemplates(tile.terType->getId()).empty())
  173. {
  174. appearance = handler->getTemplates(tile.terType->getId())[0];
  175. }
  176. else
  177. {
  178. logGlobal->warn("Object %d:%d at %s has no templates suitable for terrain %s", ID, subID, visitablePos().toString(), tile.terType->getNameTranslated());
  179. appearance = handler->getTemplates()[0]; // get at least some appearance since alternative is crash
  180. }
  181. if(this->ID == Obj::PRISON && ID == Obj::HERO)
  182. {
  183. auto newOffset = getVisitableOffset();
  184. // FIXME: potentially unused code - setType is NOT called when releasing hero from prison
  185. // instead, appearance update & pos adjustment occurs in GiveHero::applyGs
  186. // adjust position since hero and prison may have different visitable offset
  187. pos = pos - oldOffset + newOffset;
  188. }
  189. this->ID = Obj(ID);
  190. this->subID = subID;
  191. cb->gameState()->map->addBlockVisTiles(this);
  192. }
  193. void CGObjectInstance::initObj(CRandomGenerator & rand)
  194. {
  195. switch(ID)
  196. {
  197. case Obj::TAVERN:
  198. blockVisit = true;
  199. break;
  200. }
  201. }
  202. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  203. {
  204. setPropertyDer(what, val); // call this before any actual changes (needed at least for dwellings)
  205. switch(what)
  206. {
  207. case ObjProperty::OWNER:
  208. tempOwner = PlayerColor(val);
  209. break;
  210. case ObjProperty::BLOCKVIS:
  211. blockVisit = val;
  212. break;
  213. case ObjProperty::ID:
  214. ID = Obj(val);
  215. break;
  216. case ObjProperty::SUBID:
  217. subID = val;
  218. break;
  219. }
  220. }
  221. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  222. {}
  223. int3 CGObjectInstance::getSightCenter() const
  224. {
  225. return visitablePos();
  226. }
  227. int CGObjectInstance::getSightRadius() const
  228. {
  229. return 3;
  230. }
  231. int3 CGObjectInstance::getVisitableOffset() const
  232. {
  233. return appearance->getVisitableOffset();
  234. }
  235. void CGObjectInstance::giveDummyBonus(const ObjectInstanceID & heroID, ui8 duration) const
  236. {
  237. GiveBonus gbonus;
  238. gbonus.bonus.type = Bonus::NONE;
  239. gbonus.id = heroID.getNum();
  240. gbonus.bonus.duration = static_cast<Bonus::BonusDuration>(duration);
  241. gbonus.bonus.source = Bonus::OBJECT;
  242. gbonus.bonus.sid = ID;
  243. cb->giveHeroBonus(&gbonus);
  244. }
  245. std::string CGObjectInstance::getObjectName() const
  246. {
  247. return VLC->objtypeh->getObjectName(ID, subID);
  248. }
  249. boost::optional<std::string> CGObjectInstance::getAmbientSound() const
  250. {
  251. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).ambient;
  252. if(!sounds.empty())
  253. return sounds.front(); // TODO: Support randomization of ambient sounds
  254. return boost::none;
  255. }
  256. boost::optional<std::string> CGObjectInstance::getVisitSound() const
  257. {
  258. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).visit;
  259. if(!sounds.empty())
  260. return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
  261. return boost::none;
  262. }
  263. boost::optional<std::string> CGObjectInstance::getRemovalSound() const
  264. {
  265. const auto & sounds = VLC->objtypeh->getObjectSounds(ID, subID).removal;
  266. if(!sounds.empty())
  267. return *RandomGeneratorUtil::nextItem(sounds, CRandomGenerator::getDefault());
  268. return boost::none;
  269. }
  270. std::string CGObjectInstance::getHoverText(PlayerColor player) const
  271. {
  272. auto text = getObjectName();
  273. if (tempOwner.isValidPlayer())
  274. text += "\n" + VLC->generaltexth->arraytxt[23 + tempOwner.getNum()];
  275. return text;
  276. }
  277. std::string CGObjectInstance::getHoverText(const CGHeroInstance * hero) const
  278. {
  279. return getHoverText(hero->tempOwner);
  280. }
  281. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  282. {
  283. switch(ID)
  284. {
  285. case Obj::HILL_FORT:
  286. {
  287. openWindow(OpenWindow::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  288. }
  289. break;
  290. case Obj::SANCTUARY:
  291. {
  292. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  293. showInfoDialog(h, 114);
  294. }
  295. break;
  296. case Obj::TAVERN:
  297. {
  298. openWindow(OpenWindow::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  299. }
  300. break;
  301. }
  302. }
  303. int3 CGObjectInstance::visitablePos() const
  304. {
  305. return pos - getVisitableOffset();
  306. }
  307. bool CGObjectInstance::isVisitable() const
  308. {
  309. return appearance->isVisitable();
  310. }
  311. bool CGObjectInstance::passableFor(PlayerColor color) const
  312. {
  313. return false;
  314. }
  315. void CGObjectInstance::updateFrom(const JsonNode & data)
  316. {
  317. }
  318. void CGObjectInstance::serializeJson(JsonSerializeFormat & handler)
  319. {
  320. //only save here, loading is handled by map loader
  321. if(handler.saving)
  322. {
  323. handler.serializeString("type", typeName);
  324. handler.serializeString("subtype", subTypeName);
  325. handler.serializeInt("x", pos.x);
  326. handler.serializeInt("y", pos.y);
  327. handler.serializeInt("l", pos.z);
  328. JsonNode app;
  329. appearance->writeJson(app, false);
  330. handler.serializeRaw("template",app, boost::none);
  331. }
  332. {
  333. auto options = handler.enterStruct("options");
  334. serializeJsonOptions(handler);
  335. }
  336. }
  337. void CGObjectInstance::afterAddToMap(CMap * map)
  338. {
  339. //nothing here
  340. }
  341. void CGObjectInstance::afterRemoveFromMap(CMap * map)
  342. {
  343. //nothing here
  344. }
  345. void CGObjectInstance::serializeJsonOptions(JsonSerializeFormat & handler)
  346. {
  347. //nothing here
  348. }
  349. void CGObjectInstance::serializeJsonOwner(JsonSerializeFormat & handler)
  350. {
  351. ui8 temp = tempOwner.getNum();
  352. handler.serializeEnum("owner", temp, PlayerColor::NEUTRAL.getNum(), GameConstants::PLAYER_COLOR_NAMES);
  353. if(!handler.saving)
  354. tempOwner = PlayerColor(temp);
  355. }
  356. BattleField CGObjectInstance::getBattlefield() const
  357. {
  358. return VLC->objtypeh->getHandlerFor(ID, subID)->getBattlefield();
  359. }
  360. CGObjectInstanceBySubIdFinder::CGObjectInstanceBySubIdFinder(CGObjectInstance * obj) : obj(obj)
  361. {
  362. }
  363. bool CGObjectInstanceBySubIdFinder::operator()(CGObjectInstance * obj) const
  364. {
  365. return this->obj->subID == obj->subID;
  366. }
  367. int3 IBoatGenerator::bestLocation() const
  368. {
  369. std::vector<int3> offsets;
  370. getOutOffsets(offsets);
  371. for (auto & offset : offsets)
  372. {
  373. if(const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  374. {
  375. if(tile->terType->isWater() && (!tile->blocked || tile->blockingObjects.front()->ID == Obj::BOAT)) //and is water and is not blocked or is blocked by boat
  376. return o->pos + offset;
  377. }
  378. }
  379. return int3 (-1,-1,-1);
  380. }
  381. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  382. {
  383. int3 tile = bestLocation();
  384. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  385. if(!t)
  386. return TILE_BLOCKED; //no available water
  387. else if(t->blockingObjects.empty())
  388. return GOOD; //OK
  389. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  390. return BOAT_ALREADY_BUILT; //blocked with boat
  391. else
  392. return TILE_BLOCKED; //blocked
  393. }
  394. int IBoatGenerator::getBoatType() const
  395. {
  396. //We make good ships by default
  397. return 1;
  398. }
  399. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  400. : o(O)
  401. {
  402. }
  403. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  404. {
  405. switch(shipyardStatus())
  406. {
  407. case BOAT_ALREADY_BUILT:
  408. out.addTxt(MetaString::GENERAL_TXT, 51);
  409. break;
  410. case TILE_BLOCKED:
  411. if(visitor)
  412. {
  413. out.addTxt(MetaString::GENERAL_TXT, 134);
  414. out.addReplacement(visitor->getNameTranslated());
  415. }
  416. else
  417. out.addTxt(MetaString::ADVOB_TXT, 189);
  418. break;
  419. case NO_WATER:
  420. logGlobal->error("Shipyard without water! %s \t %d", o->pos.toString(), o->id.getNum());
  421. return;
  422. }
  423. }
  424. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  425. {
  426. cost.resize(GameConstants::RESOURCE_QUANTITY);
  427. cost[Res::WOOD] = 10;
  428. cost[Res::GOLD] = 1000;
  429. }
  430. IShipyard::IShipyard(const CGObjectInstance *O)
  431. : IBoatGenerator(O)
  432. {
  433. }
  434. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  435. {
  436. if(!obj)
  437. return nullptr;
  438. if(obj->ID == Obj::TOWN)
  439. {
  440. return dynamic_cast<CGTownInstance *>(obj);
  441. }
  442. else if(obj->ID == Obj::SHIPYARD)
  443. {
  444. return dynamic_cast<CGShipyard *>(obj);
  445. }
  446. else
  447. {
  448. return nullptr;
  449. }
  450. }
  451. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  452. {
  453. return castFrom(const_cast<CGObjectInstance*>(obj));
  454. }
  455. VCMI_LIB_NAMESPACE_END