2
0

CObjectClassesHandler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. * CObjectClassesHandler.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 "CObjectClassesHandler.h"
  12. #include "../filesystem/Filesystem.h"
  13. #include "../filesystem/CBinaryReader.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../GameConstants.h"
  16. #include "../StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "../CModHandler.h"
  19. #include "../JsonNode.h"
  20. #include "../CSoundBase.h"
  21. #include "CRewardableConstructor.h"
  22. #include "CommonConstructors.h"
  23. #include "MapObjects.h"
  24. // FIXME: move into inheritNode?
  25. static void inheritNodeWithMeta(JsonNode & descendant, const JsonNode & base)
  26. {
  27. std::string oldMeta = descendant.meta;
  28. JsonUtils::inherit(descendant, base);
  29. descendant.setMeta(oldMeta);
  30. }
  31. CObjectClassesHandler::CObjectClassesHandler()
  32. {
  33. #define SET_HANDLER_CLASS(STRING, CLASSNAME) handlerConstructors[STRING] = std::make_shared<CLASSNAME>;
  34. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME>>
  35. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  36. //Note: should be in sync with registerTypesMapObjectTypes function
  37. SET_HANDLER_CLASS("configurable", CRewardableConstructor);
  38. SET_HANDLER_CLASS("dwelling", CDwellingInstanceConstructor);
  39. SET_HANDLER_CLASS("hero", CHeroInstanceConstructor);
  40. SET_HANDLER_CLASS("town", CTownInstanceConstructor);
  41. SET_HANDLER_CLASS("bank", CBankInstanceConstructor);
  42. SET_HANDLER_CLASS("static", CObstacleConstructor);
  43. SET_HANDLER_CLASS("", CObstacleConstructor);
  44. SET_HANDLER("randomArtifact", CGArtifact);
  45. SET_HANDLER("randomHero", CGHeroInstance);
  46. SET_HANDLER("randomResource", CGResource);
  47. SET_HANDLER("randomTown", CGTownInstance);
  48. SET_HANDLER("randomMonster", CGCreature);
  49. SET_HANDLER("randomDwelling", CGDwelling);
  50. SET_HANDLER("generic", CGObjectInstance);
  51. SET_HANDLER("market", CGMarket);
  52. SET_HANDLER("cartographer", CCartographer);
  53. SET_HANDLER("artifact", CGArtifact);
  54. SET_HANDLER("blackMarket", CGBlackMarket);
  55. SET_HANDLER("boat", CGBoat);
  56. SET_HANDLER("bonusingObject", CGBonusingObject);
  57. SET_HANDLER("borderGate", CGBorderGate);
  58. SET_HANDLER("borderGuard", CGBorderGuard);
  59. SET_HANDLER("monster", CGCreature);
  60. SET_HANDLER("denOfThieves", CGDenOfthieves);
  61. SET_HANDLER("event", CGEvent);
  62. SET_HANDLER("garrison", CGGarrison);
  63. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  64. SET_HANDLER("keymaster", CGKeymasterTent);
  65. SET_HANDLER("lighthouse", CGLighthouse);
  66. SET_HANDLER("magi", CGMagi);
  67. SET_HANDLER("magicSpring", CGMagicSpring);
  68. SET_HANDLER("magicWell", CGMagicWell);
  69. SET_HANDLER("market", CGMarket);
  70. SET_HANDLER("mine", CGMine);
  71. SET_HANDLER("obelisk", CGObelisk);
  72. SET_HANDLER("observatory", CGObservatory);
  73. SET_HANDLER("onceVisitable", CGOnceVisitable);
  74. SET_HANDLER("pandora", CGPandoraBox);
  75. SET_HANDLER("pickable", CGPickable);
  76. SET_HANDLER("prison", CGHeroInstance);
  77. SET_HANDLER("questGuard", CGQuestGuard);
  78. SET_HANDLER("resource", CGResource);
  79. SET_HANDLER("scholar", CGScholar);
  80. SET_HANDLER("seerHut", CGSeerHut);
  81. SET_HANDLER("shipyard", CGShipyard);
  82. SET_HANDLER("shrine", CGShrine);
  83. SET_HANDLER("sign", CGSignBottle);
  84. SET_HANDLER("siren", CGSirens);
  85. SET_HANDLER("monolith", CGMonolith);
  86. SET_HANDLER("subterraneanGate", CGSubterraneanGate);
  87. SET_HANDLER("whirlpool", CGWhirlpool);
  88. SET_HANDLER("university", CGUniversity);
  89. SET_HANDLER("oncePerHero", CGVisitableOPH);
  90. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  91. SET_HANDLER("witch", CGWitchHut);
  92. #undef SET_HANDLER_CLASS
  93. #undef SET_HANDLER
  94. }
  95. CObjectClassesHandler::~CObjectClassesHandler()
  96. {
  97. for(auto p : objects)
  98. delete p.second;
  99. }
  100. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  101. {
  102. CLegacyConfigParser parser("Data/Objects.txt");
  103. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  104. parser.endLine();
  105. for (size_t i=0; i<totalNumber; i++)
  106. {
  107. ObjectTemplate templ;
  108. templ.readTxt(parser);
  109. parser.endLine();
  110. std::pair<si32, si32> key(templ.id.num, templ.subid);
  111. legacyTemplates.insert(std::make_pair(key, templ));
  112. }
  113. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  114. assert(dataSize == 256);
  115. CLegacyConfigParser namesParser("Data/ObjNames.txt");
  116. for (size_t i=0; i<256; i++)
  117. {
  118. ret[i]["name"].String() = namesParser.readString();
  119. namesParser.endLine();
  120. }
  121. CLegacyConfigParser cregen1Parser("data/crgen1");
  122. do
  123. customNames[Obj::CREATURE_GENERATOR1].push_back(cregen1Parser.readString());
  124. while(cregen1Parser.endLine());
  125. CLegacyConfigParser cregen4Parser("data/crgen4");
  126. do
  127. customNames[Obj::CREATURE_GENERATOR4].push_back(cregen4Parser.readString());
  128. while(cregen4Parser.endLine());
  129. return ret;
  130. }
  131. /// selects preferred ID (or subID) for new object
  132. template<typename Map>
  133. si32 selectNextID(const JsonNode & fixedID, const Map & map, si32 defaultID)
  134. {
  135. if (!fixedID.isNull() && fixedID.Float() < defaultID)
  136. return fixedID.Float(); // H3M object with fixed ID
  137. if (map.empty())
  138. return defaultID; // no objects loaded, keep gap for H3M objects
  139. if (map.rbegin()->first >= defaultID)
  140. return map.rbegin()->first + 1; // some modded objects loaded, return next available
  141. return defaultID; // some H3M objects loaded, first modded found
  142. }
  143. void CObjectClassesHandler::loadObjectEntry(const std::string & identifier, const JsonNode & entry, ObjectContainter * obj)
  144. {
  145. if (!handlerConstructors.count(obj->handlerName))
  146. {
  147. logGlobal->error("Handler with name %s was not found!", obj->handlerName);
  148. return;
  149. }
  150. std::string convertedId = VLC->modh->normalizeIdentifier(entry.meta, "core", identifier);
  151. si32 id = selectNextID(entry["index"], obj->subObjects, 1000);
  152. auto handler = handlerConstructors.at(obj->handlerName)();
  153. handler->setType(obj->id, id);
  154. handler->setTypeName(obj->identifier, convertedId);
  155. if (customNames.count(obj->id) && customNames.at(obj->id).size() > id)
  156. handler->init(entry, customNames.at(obj->id).at(id));
  157. else
  158. handler->init(entry);
  159. if (handler->getTemplates().empty())
  160. {
  161. auto range = legacyTemplates.equal_range(std::make_pair(obj->id, id));
  162. for (auto & templ : boost::make_iterator_range(range.first, range.second))
  163. {
  164. handler->addTemplate(templ.second);
  165. }
  166. legacyTemplates.erase(range.first, range.second);
  167. }
  168. logGlobal->debug("Loaded object %s(%d)::%s(%d)", obj->identifier, obj->id, convertedId, id);
  169. assert(!obj->subObjects.count(id)); // DO NOT override
  170. obj->subObjects[id] = handler;
  171. obj->subIds[convertedId] = id;
  172. }
  173. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json, const std::string & name)
  174. {
  175. auto obj = new ObjectContainter();
  176. obj->identifier = name;
  177. obj->name = json["name"].String();
  178. obj->handlerName = json["handler"].String();
  179. obj->base = json["base"];
  180. obj->id = selectNextID(json["index"], objects, 256);
  181. if(json["defaultAiValue"].isNull())
  182. obj->groupDefaultAiValue = boost::none;
  183. else
  184. obj->groupDefaultAiValue = json["defaultAiValue"].Integer();
  185. for (auto entry : json["types"].Struct())
  186. {
  187. loadObjectEntry(entry.first, entry.second, obj);
  188. }
  189. return obj;
  190. }
  191. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  192. {
  193. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  194. objects[object->id] = object;
  195. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  196. }
  197. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  198. {
  199. auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
  200. assert(objects[index] == nullptr); // ensure that this id was not loaded before
  201. objects[index] = object;
  202. VLC->modh->identifiers.registerObject(scope, "object", name, object->id);
  203. }
  204. void CObjectClassesHandler::loadSubObject(const std::string & identifier, JsonNode config, si32 ID, boost::optional<si32> subID)
  205. {
  206. config.setType(JsonNode::JsonType::DATA_STRUCT); // ensure that input is not NULL
  207. assert(objects.count(ID));
  208. if (subID)
  209. {
  210. assert(objects.at(ID)->subObjects.count(subID.get()) == 0);
  211. assert(config["index"].isNull());
  212. config["index"].Float() = subID.get();
  213. }
  214. inheritNodeWithMeta(config, objects.at(ID)->base);
  215. loadObjectEntry(identifier, config, objects[ID]);
  216. }
  217. void CObjectClassesHandler::removeSubObject(si32 ID, si32 subID)
  218. {
  219. assert(objects.count(ID));
  220. assert(objects.at(ID)->subObjects.count(subID));
  221. objects.at(ID)->subObjects.erase(subID); //TODO: cleanup string id map
  222. }
  223. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  224. {
  225. return std::vector<bool>(); //TODO?
  226. }
  227. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  228. {
  229. if (objects.count(type))
  230. {
  231. if (objects.at(type)->subObjects.count(subtype))
  232. return objects.at(type)->subObjects.at(subtype);
  233. }
  234. logGlobal->error("Failed to find object of type %d:%d", type, subtype);
  235. throw std::runtime_error("Object type handler not found");
  236. }
  237. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(std::string type, std::string subtype) const
  238. {
  239. boost::optional<si32> id = VLC->modh->identifiers.getIdentifier("core", "object", type, false);
  240. if(id)
  241. {
  242. auto object = objects.at(id.get());
  243. if(object->subIds.count(subtype))
  244. {
  245. si32 subId = object->subIds.at(subtype);
  246. return object->subObjects.at(subId);
  247. }
  248. }
  249. logGlobal->error("Failed to find object of type %s::%s", type, subtype);
  250. throw std::runtime_error("Object type handler not found");
  251. }
  252. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(CompoundMapObjectID compoundIdentifier) const
  253. {
  254. return getHandlerFor(compoundIdentifier.primaryID, compoundIdentifier.secondaryID);
  255. }
  256. std::set<si32> CObjectClassesHandler::knownObjects() const
  257. {
  258. std::set<si32> ret;
  259. for (auto entry : objects)
  260. ret.insert(entry.first);
  261. return ret;
  262. }
  263. std::set<si32> CObjectClassesHandler::knownSubObjects(si32 primaryID) const
  264. {
  265. std::set<si32> ret;
  266. if (objects.count(primaryID))
  267. {
  268. for (auto entry : objects.at(primaryID)->subObjects)
  269. ret.insert(entry.first);
  270. }
  271. return ret;
  272. }
  273. void CObjectClassesHandler::beforeValidate(JsonNode & object)
  274. {
  275. for (auto & entry : object["types"].Struct())
  276. {
  277. inheritNodeWithMeta(entry.second, object["base"]);
  278. for (auto & templ : entry.second["templates"].Struct())
  279. {
  280. inheritNodeWithMeta(templ.second, entry.second["base"]);
  281. }
  282. }
  283. }
  284. void CObjectClassesHandler::afterLoadFinalization()
  285. {
  286. for(auto entry : objects)
  287. {
  288. for(auto obj : entry.second->subObjects)
  289. {
  290. obj.second->afterLoadFinalization();
  291. if(obj.second->getTemplates().empty())
  292. logGlobal->warn("No templates found for %d:%d", entry.first, obj.first);
  293. }
  294. }
  295. //duplicate existing two-way portals to make reserve for RMG
  296. auto& portalVec = objects[Obj::MONOLITH_TWO_WAY]->subObjects;
  297. size_t portalCount = portalVec.size();
  298. size_t currentIndex = portalCount;
  299. while(portalVec.size() < 100)
  300. {
  301. portalVec[currentIndex] = portalVec[currentIndex % portalCount];
  302. currentIndex++;
  303. }
  304. }
  305. std::string CObjectClassesHandler::getObjectName(si32 type) const
  306. {
  307. if (objects.count(type))
  308. return objects.at(type)->name;
  309. logGlobal->error("Access to non existing object of type %d", type);
  310. return "";
  311. }
  312. std::string CObjectClassesHandler::getObjectName(si32 type, si32 subtype) const
  313. {
  314. if (knownSubObjects(type).count(subtype))
  315. {
  316. auto name = getHandlerFor(type, subtype)->getCustomName();
  317. if (name)
  318. return name.get();
  319. }
  320. return getObjectName(type);
  321. }
  322. SObjectSounds CObjectClassesHandler::getObjectSounds(si32 type) const
  323. {
  324. if(objects.count(type))
  325. return objects.at(type)->sounds;
  326. logGlobal->error("Access to non existing object of type %d", type);
  327. return SObjectSounds();
  328. }
  329. SObjectSounds CObjectClassesHandler::getObjectSounds(si32 type, si32 subtype) const
  330. {
  331. if(knownSubObjects(type).count(subtype))
  332. return getHandlerFor(type, subtype)->getSounds();
  333. else
  334. return getObjectSounds(type);
  335. }
  336. std::string CObjectClassesHandler::getObjectHandlerName(si32 type) const
  337. {
  338. return objects.at(type)->handlerName;
  339. }
  340. boost::optional<si32> CObjectClassesHandler::getObjGroupAiValue(si32 primaryID) const
  341. {
  342. return objects.at(primaryID)->groupDefaultAiValue;
  343. }
  344. AObjectTypeHandler::AObjectTypeHandler():
  345. type(-1), subtype(-1)
  346. {
  347. }
  348. AObjectTypeHandler::~AObjectTypeHandler()
  349. {
  350. }
  351. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  352. {
  353. this->type = type;
  354. this->subtype = subtype;
  355. }
  356. void AObjectTypeHandler::setTypeName(std::string type, std::string subtype)
  357. {
  358. this->typeName = type;
  359. this->subTypeName = subtype;
  360. }
  361. static ui32 loadJsonOrMax(const JsonNode & input)
  362. {
  363. if (input.isNull())
  364. return std::numeric_limits<ui32>::max();
  365. else
  366. return input.Float();
  367. }
  368. void AObjectTypeHandler::init(const JsonNode & input, boost::optional<std::string> name)
  369. {
  370. base = input["base"];
  371. if (!input["rmg"].isNull())
  372. {
  373. rmgInfo.value = input["rmg"]["value"].Float();
  374. rmgInfo.mapLimit = loadJsonOrMax(input["rmg"]["mapLimit"]);
  375. rmgInfo.zoneLimit = loadJsonOrMax(input["rmg"]["zoneLimit"]);
  376. rmgInfo.rarity = input["rmg"]["rarity"].Float();
  377. } // else block is not needed - set in constructor
  378. for (auto entry : input["templates"].Struct())
  379. {
  380. entry.second.setType(JsonNode::JsonType::DATA_STRUCT);
  381. JsonUtils::inherit(entry.second, base);
  382. ObjectTemplate tmpl;
  383. tmpl.id = Obj(type);
  384. tmpl.subid = subtype;
  385. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  386. tmpl.readJson(entry.second);
  387. templates.push_back(tmpl);
  388. }
  389. if (input["name"].isNull())
  390. objectName = name;
  391. else
  392. objectName.reset(input["name"].String());
  393. for(const JsonNode & node : input["sounds"]["ambient"].Vector())
  394. sounds.ambient.push_back(node.String());
  395. for(const JsonNode & node : input["sounds"]["visit"].Vector())
  396. sounds.visit.push_back(node.String());
  397. for(const JsonNode & node : input["sounds"]["removal"].Vector())
  398. sounds.removal.push_back(node.String());
  399. if(input["aiValue"].isNull())
  400. aiValue = boost::none;
  401. else
  402. aiValue = input["aiValue"].Integer();
  403. initTypeData(input);
  404. }
  405. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  406. {
  407. return false; // by default there are no overrides
  408. }
  409. void AObjectTypeHandler::preInitObject(CGObjectInstance * obj) const
  410. {
  411. obj->ID = Obj(type);
  412. obj->subID = subtype;
  413. obj->typeName = typeName;
  414. obj->subTypeName = subTypeName;
  415. }
  416. void AObjectTypeHandler::initTypeData(const JsonNode & input)
  417. {
  418. // empty implementation for overrides
  419. }
  420. boost::optional<std::string> AObjectTypeHandler::getCustomName() const
  421. {
  422. return objectName;
  423. }
  424. SObjectSounds AObjectTypeHandler::getSounds() const
  425. {
  426. return sounds;
  427. }
  428. void AObjectTypeHandler::addTemplate(const ObjectTemplate & templ)
  429. {
  430. templates.push_back(templ);
  431. templates.back().id = Obj(type);
  432. templates.back().subid = subtype;
  433. }
  434. void AObjectTypeHandler::addTemplate(JsonNode config)
  435. {
  436. config.setType(JsonNode::JsonType::DATA_STRUCT); // ensure that input is not null
  437. JsonUtils::inherit(config, base);
  438. ObjectTemplate tmpl;
  439. tmpl.id = Obj(type);
  440. tmpl.subid = subtype;
  441. tmpl.stringID = ""; // TODO?
  442. tmpl.readJson(config);
  443. templates.push_back(tmpl);
  444. }
  445. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  446. {
  447. return templates;
  448. }
  449. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  450. {
  451. std::vector<ObjectTemplate> templates = getTemplates();
  452. std::vector<ObjectTemplate> filtered;
  453. std::copy_if(templates.begin(), templates.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  454. {
  455. return obj.canBePlacedAt(ETerrainType(terrainType));
  456. });
  457. // H3 defines allowed terrains in a weird way - artifacts, monsters and resources have faulty masks here
  458. // Perhaps we should re-define faulty templates and remove this workaround (already done for resources)
  459. if (type == Obj::ARTIFACT || type == Obj::MONSTER)
  460. return templates;
  461. else
  462. return filtered;
  463. }
  464. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  465. {
  466. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  467. for (auto & tmpl : ret)
  468. {
  469. if (objectFilter(object, tmpl))
  470. return tmpl;
  471. }
  472. return boost::optional<ObjectTemplate>();
  473. }
  474. const RandomMapInfo & AObjectTypeHandler::getRMGInfo()
  475. {
  476. return rmgInfo;
  477. }
  478. boost::optional<si32> AObjectTypeHandler::getAiValue() const
  479. {
  480. return aiValue;
  481. }
  482. bool AObjectTypeHandler::isStaticObject()
  483. {
  484. return false; // most of classes are not static
  485. }
  486. void AObjectTypeHandler::afterLoadFinalization()
  487. {
  488. }