CDefObjInfoHandler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. #include "StdInc.h"
  2. #include "CDefObjInfoHandler.h"
  3. #include "filesystem/Filesystem.h"
  4. #include "filesystem/CBinaryReader.h"
  5. #include "../lib/VCMI_Lib.h"
  6. #include "GameConstants.h"
  7. #include "StringConstants.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CObjectHandler.h"
  10. #include "CModHandler.h"
  11. #include "JsonNode.h"
  12. #include "CObjectConstructor.h"
  13. /*
  14. * CDefObjInfoHandler.cpp, part of VCMI engine
  15. *
  16. * Authors: listed in file AUTHORS in main folder
  17. *
  18. * License: GNU General Public License v2.0 or later
  19. * Full text of license available in license.txt file, in main folder
  20. *
  21. */
  22. static bool isVisitableFromTop(int identifier, int type)
  23. {
  24. if(type == 2 || type == 3 || type == 4 || type == 5) //creature, hero, artifact, resource
  25. return true;
  26. static const Obj visitableFromTop[] =
  27. {Obj::FLOTSAM,
  28. Obj::SEA_CHEST,
  29. Obj::SHIPWRECK_SURVIVOR,
  30. Obj::BUOY,
  31. Obj::OCEAN_BOTTLE,
  32. Obj::BOAT,
  33. Obj::WHIRLPOOL,
  34. Obj::GARRISON,
  35. Obj::GARRISON2,
  36. Obj::SCHOLAR,
  37. Obj::CAMPFIRE,
  38. Obj::BORDERGUARD,
  39. Obj::BORDER_GATE,
  40. Obj::QUEST_GUARD,
  41. Obj::CORPSE
  42. };
  43. if (vstd::find_pos(visitableFromTop, identifier) != -1)
  44. return true;
  45. return false;
  46. }
  47. ObjectTemplate::ObjectTemplate():
  48. visitDir(8|16|32|64|128), // all but top
  49. id(Obj::NO_OBJ),
  50. subid(0),
  51. printPriority(0)
  52. {
  53. }
  54. void ObjectTemplate::readTxt(CLegacyConfigParser & parser)
  55. {
  56. std::string data = parser.readString();
  57. std::vector<std::string> strings;
  58. boost::split(strings, data, boost::is_any_of(" "));
  59. assert(strings.size() == 9);
  60. animationFile = strings[0];
  61. stringID = strings[0];
  62. std::string & blockStr = strings[1]; //block map, 0 = blocked, 1 = unblocked
  63. std::string & visitStr = strings[2]; //visit map, 1 = visitable, 0 = not visitable
  64. assert(blockStr.size() == 6*8);
  65. assert(visitStr.size() == 6*8);
  66. setSize(8, 6);
  67. for (size_t i=0; i<6; i++) // 6 rows
  68. {
  69. for (size_t j=0; j<8; j++) // 8 columns
  70. {
  71. auto & tile = usedTiles[i][j];
  72. tile |= VISIBLE; // assume that all tiles are visible
  73. if (blockStr[i*8 + j] == '0')
  74. tile |= BLOCKED;
  75. if (visitStr[i*8 + j] == '1')
  76. tile |= VISITABLE;
  77. }
  78. }
  79. // strings[3] most likely - terrains on which this object can be placed in editor.
  80. // e.g. Whirpool can be placed manually only on water while mines can be placed everywhere despite terrain-specific gfx
  81. // so these two fields can be interpreted as "strong affinity" and "weak affinity" towards terrains
  82. std::string & terrStr = strings[4]; // allowed terrains, 1 = object can be placed on this terrain
  83. assert(terrStr.size() == 9); // all terrains but rock
  84. for (size_t i=0; i<9; i++)
  85. {
  86. if (terrStr[8-i] == '1')
  87. allowedTerrains.insert(ETerrainType(i));
  88. }
  89. id = Obj(boost::lexical_cast<int>(strings[5]));
  90. subid = boost::lexical_cast<int>(strings[6]);
  91. int type = boost::lexical_cast<int>(strings[7]);
  92. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  93. if (isVisitableFromTop(id, type))
  94. visitDir = 0xff;
  95. else
  96. visitDir = (8|16|32|64|128);
  97. readMsk();
  98. }
  99. void ObjectTemplate::readMsk()
  100. {
  101. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  102. if (CResourceHandler::get()->existsResource(resID))
  103. {
  104. auto msk = CResourceHandler::get()->load(resID)->readAll();
  105. setSize(msk.first.get()[0], msk.first.get()[1]);
  106. }
  107. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  108. {
  109. setSize(8, 6);
  110. }
  111. }
  112. void ObjectTemplate::readMap(CBinaryReader & reader)
  113. {
  114. animationFile = reader.readString();
  115. setSize(8, 6);
  116. ui8 blockMask[6];
  117. ui8 visitMask[6];
  118. for(auto & byte : blockMask)
  119. byte = reader.readUInt8();
  120. for(auto & byte : visitMask)
  121. byte = reader.readUInt8();
  122. for (size_t i=0; i<6; i++) // 6 rows
  123. {
  124. for (size_t j=0; j<8; j++) // 8 columns
  125. {
  126. auto & tile = usedTiles[5 - i][7 - j];
  127. tile |= VISIBLE; // assume that all tiles are visible
  128. if (((blockMask[i] >> j) & 1 ) == 0)
  129. tile |= BLOCKED;
  130. if (((visitMask[i] >> j) & 1 ) != 0)
  131. tile |= VISITABLE;
  132. }
  133. }
  134. reader.readUInt16();
  135. ui16 terrMask = reader.readUInt16();
  136. for (size_t i=0; i<9; i++)
  137. {
  138. if (((terrMask >> i) & 1 ) != 0)
  139. allowedTerrains.insert(ETerrainType(i));
  140. }
  141. id = Obj(reader.readUInt32());
  142. subid = reader.readUInt32();
  143. int type = reader.readUInt8();
  144. printPriority = reader.readUInt8() * 100; // to have some space in future
  145. if (isVisitableFromTop(id, type))
  146. visitDir = 0xff;
  147. else
  148. visitDir = (8|16|32|64|128);
  149. reader.skip(16);
  150. readMsk();
  151. if (id == Obj::EVENT)
  152. {
  153. setSize(1,1);
  154. usedTiles[0][0] = VISITABLE;
  155. }
  156. }
  157. void ObjectTemplate::readJson(const JsonNode &node)
  158. {
  159. //id = Obj(node["basebase"].Float()); // temporary, should be removed and determined indirectly via object type parent (e.g. base->base)
  160. //subid = node["base"].Float();
  161. animationFile = node["animation"].String();
  162. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  163. if (!visitDirs.empty())
  164. {
  165. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  166. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  167. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  168. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  169. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  170. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  171. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  172. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  173. }
  174. else
  175. visitDir = 0x00;
  176. if (!node["allowedTerrains"].isNull())
  177. {
  178. for (auto & entry : node["allowedTerrains"].Vector())
  179. allowedTerrains.insert(ETerrainType(vstd::find_pos(GameConstants::TERRAIN_NAMES, entry.String())));
  180. }
  181. else
  182. {
  183. for (size_t i=0; i< GameConstants::TERRAIN_TYPES; i++)
  184. allowedTerrains.insert(ETerrainType(i));
  185. }
  186. auto charToTile = [&](const char & ch) -> ui8
  187. {
  188. switch (ch)
  189. {
  190. case ' ' : return 0;
  191. case '0' : return 0;
  192. case 'V' : return VISIBLE;
  193. case 'B' : return VISIBLE | BLOCKED;
  194. case 'H' : return BLOCKED;
  195. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  196. case 'T' : return BLOCKED | VISITABLE;
  197. default:
  198. logGlobal->errorStream() << "Unrecognized char " << ch << " in template mask";
  199. return 0;
  200. }
  201. };
  202. const JsonVector & mask = node["mask"].Vector();
  203. size_t height = mask.size();
  204. size_t width = 0;
  205. for (auto & line : mask)
  206. vstd::amax(width, line.String().size());
  207. setSize(width, height);
  208. for (size_t i=0; i<mask.size(); i++)
  209. {
  210. const std::string & line = mask[i].String();
  211. for (size_t j=0; j < line.size(); j++)
  212. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  213. }
  214. printPriority = node["zIndex"].Float();
  215. }
  216. ui32 ObjectTemplate::getWidth() const
  217. {
  218. return usedTiles.empty() ? 0 : usedTiles.front().size();
  219. }
  220. ui32 ObjectTemplate::getHeight() const
  221. {
  222. return usedTiles.size();
  223. }
  224. void ObjectTemplate::setSize(ui32 width, ui32 height)
  225. {
  226. usedTiles.resize(height);
  227. for (auto & line : usedTiles)
  228. line.resize(width, 0);
  229. }
  230. bool ObjectTemplate::isVisitable() const
  231. {
  232. for (auto & line : usedTiles)
  233. for (auto & tile : line)
  234. if (tile & VISITABLE)
  235. return true;
  236. return false;
  237. }
  238. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  239. {
  240. if (X < 0 || Y < 0)
  241. return false;
  242. if (X >= getWidth() || Y >= getHeight())
  243. return false;
  244. return true;
  245. }
  246. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  247. {
  248. if (isWithin(X, Y))
  249. return usedTiles[Y][X] & VISITABLE;
  250. return false;
  251. }
  252. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  253. {
  254. if (isWithin(X, Y))
  255. return usedTiles[Y][X] & VISIBLE;
  256. return false;
  257. }
  258. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  259. {
  260. if (isWithin(X, Y))
  261. return usedTiles[Y][X] & BLOCKED;
  262. return false;
  263. }
  264. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  265. {
  266. // visitDir uses format
  267. // 1 2 3
  268. // 8 4
  269. // 7 6 5
  270. int dirMap[3][3] =
  271. {
  272. { visitDir & 1, visitDir & 2, visitDir & 4 },
  273. { visitDir & 128, 1 , visitDir & 8 },
  274. { visitDir & 64, visitDir & 32, visitDir & 16 }
  275. };
  276. // map input values to range 0..2
  277. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  278. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  279. return dirMap[dy][dx] != 0;
  280. }
  281. bool ObjectTemplate::canBePlacedAt(ETerrainType terrain) const
  282. {
  283. return allowedTerrains.count(terrain) != 0;
  284. }
  285. /*
  286. void CDefObjInfoHandler::readTextFile(std::string path)
  287. {
  288. CLegacyConfigParser parser(path);
  289. size_t totalNumber = parser.readNumber(); // first line contains number of objects to read and nothing else
  290. parser.endLine();
  291. for (size_t i=0; i<totalNumber; i++)
  292. {
  293. ObjectTemplate templ;
  294. templ.readTxt(parser);
  295. parser.endLine();
  296. objects.push_back(templ);
  297. }
  298. }
  299. CDefObjInfoHandler::CDefObjInfoHandler()
  300. {
  301. readTextFile("Data/Objects.txt");
  302. readTextFile("Data/Heroes.txt");
  303. }
  304. */
  305. CObjectClassesHandler::CObjectClassesHandler()
  306. {
  307. // list of all known handlers, hardcoded for now since the only way to add new objects is via C++ code
  308. handlerConstructors["configurable"] = std::make_shared<CObjectWithRewardConstructor>;
  309. #define SET_HANDLER(STRING, TYPENAME) handlerConstructors[STRING] = std::make_shared<CDefaultObjectTypeHandler<TYPENAME> >
  310. SET_HANDLER("", CGObjectInstance);
  311. SET_HANDLER("generic", CGObjectInstance);
  312. SET_HANDLER("market", CGMarket);
  313. SET_HANDLER("bank", CBank);
  314. SET_HANDLER("cartographer", CCartographer);
  315. SET_HANDLER("artifact", CGArtifact);
  316. SET_HANDLER("blackMarket", CGBlackMarket);
  317. SET_HANDLER("boat", CGBoat);
  318. SET_HANDLER("bonusingObject", CGBonusingObject);
  319. SET_HANDLER("borderGate", CGBorderGate);
  320. SET_HANDLER("borderGuard", CGBorderGuard);
  321. SET_HANDLER("monster", CGCreature);
  322. SET_HANDLER("denOfThieves", CGDenOfthieves);
  323. SET_HANDLER("dwelling", CGDwelling);
  324. SET_HANDLER("event", CGEvent);
  325. SET_HANDLER("garrison", CGGarrison);
  326. SET_HANDLER("hero", CGHeroInstance);
  327. SET_HANDLER("heroPlaceholder", CGHeroPlaceholder);
  328. SET_HANDLER("keymaster", CGKeymasterTent);
  329. SET_HANDLER("lighthouse", CGLighthouse);
  330. SET_HANDLER("magi", CGMagi);
  331. SET_HANDLER("magicSpring", CGMagicSpring);
  332. SET_HANDLER("magicWell", CGMagicWell);
  333. SET_HANDLER("market", CGMarket);
  334. SET_HANDLER("mine", CGMine);
  335. SET_HANDLER("obelisk", CGObelisk);
  336. SET_HANDLER("observatory", CGObservatory);
  337. SET_HANDLER("onceVisitable", CGOnceVisitable);
  338. SET_HANDLER("pandora", CGPandoraBox);
  339. SET_HANDLER("pickable", CGPickable);
  340. SET_HANDLER("pyramid", CGPyramid);
  341. SET_HANDLER("questGuard", CGQuestGuard);
  342. SET_HANDLER("resource", CGResource);
  343. SET_HANDLER("scholar", CGScholar);
  344. SET_HANDLER("seerHut", CGSeerHut);
  345. SET_HANDLER("shipyard", CGShipyard);
  346. SET_HANDLER("shrine", CGShrine);
  347. SET_HANDLER("sign", CGSignBottle);
  348. SET_HANDLER("siren", CGSirens);
  349. SET_HANDLER("teleport", CGTeleport);
  350. SET_HANDLER("town", CGTownInstance);
  351. SET_HANDLER("university", CGUniversity);
  352. SET_HANDLER("oncePerHero", CGVisitableOPH);
  353. SET_HANDLER("oncePerWeek", CGVisitableOPW);
  354. SET_HANDLER("witch", CGWitchHut);
  355. #undef SET_HANDLER
  356. }
  357. static std::vector<JsonNode> readTextFile(std::string path)
  358. {
  359. //TODO
  360. }
  361. std::vector<JsonNode> CObjectClassesHandler::loadLegacyData(size_t dataSize)
  362. {
  363. std::vector<JsonNode> ret(dataSize);// create storage for 256 objects
  364. auto parseFile = [&](std::string filename)
  365. {
  366. auto entries = readTextFile(filename);
  367. for (JsonNode & entry : entries)
  368. {
  369. si32 id = entry["basebase"].Float();
  370. si32 subid = entry["base"].Float();
  371. entry.Struct().erase("basebase");
  372. entry.Struct().erase("base");
  373. if (ret[id].Vector().size() <= subid)
  374. ret[id].Vector().resize(subid+1);
  375. ret[id]["legacyTypes"].Vector()[subid][entry["animation"].String()].swap(entry);
  376. }
  377. };
  378. parseFile("Data/Objects.txt");
  379. parseFile("Data/Heroes.txt");
  380. CLegacyConfigParser parser("Data/ObjNames.txt");
  381. for (size_t i=0; i<256; i++)
  382. {
  383. ret[i]["name"].String() = parser.readString();
  384. parser.endLine();
  385. }
  386. return ret;
  387. }
  388. CObjectClassesHandler::ObjectContainter * CObjectClassesHandler::loadFromJson(const JsonNode & json)
  389. {
  390. auto obj = new ObjectContainter();
  391. obj->name = json["name"].String();
  392. obj->handlerName = json["handler"].String();
  393. obj->base = json["base"];
  394. for (auto entry : json["types"].Struct())
  395. {
  396. auto handler = handlerConstructors.at(obj->handlerName)();
  397. handler->init(entry.second);
  398. }
  399. return obj;
  400. }
  401. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  402. {
  403. }
  404. void CObjectClassesHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  405. {
  406. }
  407. std::vector<bool> CObjectClassesHandler::getDefaultAllowed() const
  408. {
  409. return std::vector<bool>(); //TODO?
  410. }
  411. TObjectTypeHandler CObjectClassesHandler::getHandlerFor(si32 type, si32 subtype) const
  412. {
  413. if (objects.count(type))
  414. {
  415. if (objects.at(type)->objects.count(subtype))
  416. return objects.at(type)->objects.at(subtype);
  417. }
  418. assert(0); // FIXME: throw error?
  419. return nullptr;
  420. }
  421. std::string CObjectClassesHandler::getObjectName(si32 type) const
  422. {
  423. assert(objects.count(type));
  424. return objects.at(type)->name;
  425. }
  426. void AObjectTypeHandler::setType(si32 type, si32 subtype)
  427. {
  428. this->type = type;
  429. this->subtype = subtype;
  430. }
  431. void AObjectTypeHandler::init(const JsonNode & input)
  432. {
  433. for (auto entry : input["templates"].Struct())
  434. {
  435. JsonNode data = input["base"];
  436. JsonUtils::merge(data, entry.second);
  437. ObjectTemplate tmpl;
  438. tmpl.id = Obj(type);
  439. tmpl.subid = subtype;
  440. tmpl.stringID = entry.first; // FIXME: create "fullID" - type.object.template?
  441. tmpl.readJson(data);
  442. templates.push_back(tmpl);
  443. }
  444. }
  445. bool AObjectTypeHandler::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  446. {
  447. return true; // by default - accept all.
  448. }
  449. void AObjectTypeHandler::addTemplate(const ObjectTemplate & templ)
  450. {
  451. templates.push_back(templ);
  452. }
  453. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates() const
  454. {
  455. return templates;
  456. }
  457. std::vector<ObjectTemplate> AObjectTypeHandler::getTemplates(si32 terrainType) const// FIXME: replace with ETerrainType
  458. {
  459. std::vector<ObjectTemplate> ret = getTemplates();
  460. std::vector<ObjectTemplate> filtered;
  461. std::copy_if(ret.begin(), ret.end(), std::back_inserter(filtered), [&](const ObjectTemplate & obj)
  462. {
  463. return obj.canBePlacedAt(ETerrainType(terrainType));
  464. });
  465. // it is possible that there are no templates usable on specific terrain. In this case - return list before filtering
  466. return filtered.empty() ? ret : filtered;
  467. }
  468. boost::optional<ObjectTemplate> AObjectTypeHandler::getOverride(si32 terrainType, const CGObjectInstance * object) const
  469. {
  470. std::vector<ObjectTemplate> ret = getTemplates(terrainType);
  471. for (auto & tmpl : ret)
  472. {
  473. if (objectFilter(object, tmpl))
  474. return tmpl;
  475. }
  476. return boost::optional<ObjectTemplate>();
  477. }