CObjectHandler.cpp 12 KB

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