ObjectTemplate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /*
  2. * ObjectTemplate.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 "CObjectHandler.h"
  19. #include "../CModHandler.h"
  20. #include "../JsonNode.h"
  21. #include "../TerrainHandler.h"
  22. #include "CRewardableConstructor.h"
  23. VCMI_LIB_NAMESPACE_BEGIN
  24. static bool isOnVisitableFromTopList(int identifier, int type)
  25. {
  26. if(type == 2 || type == 3 || type == 4 || type == 5) //creature, hero, artifact, resource
  27. return true;
  28. static const Obj visitableFromTop[] =
  29. {Obj::FLOTSAM,
  30. Obj::SEA_CHEST,
  31. Obj::SHIPWRECK_SURVIVOR,
  32. Obj::BUOY,
  33. Obj::OCEAN_BOTTLE,
  34. Obj::BOAT,
  35. Obj::WHIRLPOOL,
  36. Obj::GARRISON,
  37. Obj::GARRISON2,
  38. Obj::SCHOLAR,
  39. Obj::CAMPFIRE,
  40. Obj::BORDERGUARD,
  41. Obj::BORDER_GATE,
  42. Obj::QUEST_GUARD,
  43. Obj::CORPSE
  44. };
  45. return vstd::find_pos(visitableFromTop, identifier) != -1;
  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. width(0),
  53. height(0),
  54. visitable(false)
  55. {
  56. }
  57. ObjectTemplate::ObjectTemplate(const ObjectTemplate& other):
  58. visitDir(other.visitDir),
  59. allowedTerrains(other.allowedTerrains),
  60. id(other.id),
  61. subid(other.subid),
  62. printPriority(other.printPriority),
  63. animationFile(other.animationFile),
  64. editorAnimationFile(other.editorAnimationFile),
  65. stringID(other.stringID),
  66. width(other.width),
  67. height(other.height),
  68. visitable(other.visitable),
  69. blockedOffsets(other.blockedOffsets),
  70. blockMapOffset(other.blockMapOffset),
  71. visitableOffset(other.visitableOffset)
  72. {
  73. //default copy constructor is failing with usedTiles this for unknown reason
  74. usedTiles.resize(other.usedTiles.size());
  75. for(size_t i = 0; i < usedTiles.size(); i++)
  76. std::copy(other.usedTiles[i].begin(), other.usedTiles[i].end(), std::back_inserter(usedTiles[i]));
  77. }
  78. ObjectTemplate & ObjectTemplate::operator=(const ObjectTemplate & rhs)
  79. {
  80. visitDir = rhs.visitDir;
  81. allowedTerrains = rhs.allowedTerrains;
  82. id = rhs.id;
  83. subid = rhs.subid;
  84. printPriority = rhs.printPriority;
  85. animationFile = rhs.animationFile;
  86. editorAnimationFile = rhs.editorAnimationFile;
  87. stringID = rhs.stringID;
  88. width = rhs.width;
  89. height = rhs.height;
  90. visitable = rhs.visitable;
  91. blockedOffsets = rhs.blockedOffsets;
  92. blockMapOffset = rhs.blockMapOffset;
  93. visitableOffset = rhs.visitableOffset;
  94. usedTiles.clear();
  95. usedTiles.resize(rhs.usedTiles.size());
  96. for(size_t i = 0; i < usedTiles.size(); i++)
  97. std::copy(rhs.usedTiles[i].begin(), rhs.usedTiles[i].end(), std::back_inserter(usedTiles[i]));
  98. return *this;
  99. }
  100. void ObjectTemplate::afterLoadFixup()
  101. {
  102. if(id == Obj::EVENT)
  103. {
  104. setSize(1,1);
  105. usedTiles[0][0] = VISITABLE;
  106. visitDir = 0xFF;
  107. }
  108. boost::algorithm::replace_all(animationFile, "\\", "/");
  109. boost::algorithm::replace_all(editorAnimationFile, "\\", "/");
  110. }
  111. void ObjectTemplate::readTxt(CLegacyConfigParser & parser)
  112. {
  113. std::string data = parser.readString();
  114. std::vector<std::string> strings;
  115. boost::split(strings, data, boost::is_any_of(" "));
  116. assert(strings.size() == 9);
  117. animationFile = strings[0];
  118. stringID = strings[0];
  119. std::string & blockStr = strings[1]; //block map, 0 = blocked, 1 = unblocked
  120. std::string & visitStr = strings[2]; //visit map, 1 = visitable, 0 = not visitable
  121. assert(blockStr.size() == 6*8);
  122. assert(visitStr.size() == 6*8);
  123. setSize(8, 6);
  124. for(size_t i = 0; i < 6; i++) // 6 rows
  125. {
  126. for(size_t j = 0; j < 8; j++) // 8 columns
  127. {
  128. auto & tile = usedTiles[i][j];
  129. tile |= VISIBLE; // assume that all tiles are visible
  130. if (blockStr[i*8 + j] == '0')
  131. tile |= BLOCKED;
  132. if (visitStr[i*8 + j] == '1')
  133. tile |= VISITABLE;
  134. }
  135. }
  136. // strings[3] most likely - terrains on which this object can be placed in editor.
  137. // e.g. Whirpool can be placed manually only on water while mines can be placed everywhere despite terrain-specific gfx
  138. // so these two fields can be interpreted as "strong affinity" and "weak affinity" towards terrains
  139. std::string & terrStr = strings[4]; // allowed terrains, 1 = object can be placed on this terrain
  140. assert(terrStr.size() == TerrainId(ETerrainId::ROCK).getNum()); // all terrains but rock - counting from 0
  141. for(TerrainId i = TerrainId(0); i < ETerrainId::ORIGINAL_REGULAR_TERRAIN_COUNT; ++i)
  142. {
  143. if (terrStr[8-i.getNum()] == '1')
  144. allowedTerrains.insert(i);
  145. }
  146. //assuming that object can be placed on other land terrains
  147. anyTerrain = allowedTerrains.size() >= 8 && !allowedTerrains.count(ETerrainId::WATER);
  148. id = Obj(boost::lexical_cast<int>(strings[5]));
  149. subid = boost::lexical_cast<int>(strings[6]);
  150. int type = boost::lexical_cast<int>(strings[7]);
  151. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  152. if (isOnVisitableFromTopList(id, type))
  153. visitDir = 0xff;
  154. else
  155. visitDir = (8|16|32|64|128);
  156. readMsk();
  157. recalculate();
  158. }
  159. void ObjectTemplate::readMsk()
  160. {
  161. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  162. if (CResourceHandler::get()->existsResource(resID))
  163. {
  164. auto msk = CResourceHandler::get()->load(resID)->readAll();
  165. setSize(msk.first.get()[0], msk.first.get()[1]);
  166. }
  167. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  168. {
  169. setSize(8, 6);
  170. }
  171. }
  172. void ObjectTemplate::readMap(CBinaryReader & reader)
  173. {
  174. animationFile = reader.readBaseString();
  175. setSize(8, 6);
  176. ui8 blockMask[6];
  177. ui8 visitMask[6];
  178. for(auto & byte : blockMask)
  179. byte = reader.readUInt8();
  180. for(auto & byte : visitMask)
  181. byte = reader.readUInt8();
  182. for(size_t i = 0; i < 6; i++) // 6 rows
  183. {
  184. for(size_t j = 0; j < 8; j++) // 8 columns
  185. {
  186. auto & tile = usedTiles[5 - i][7 - j];
  187. tile |= VISIBLE; // assume that all tiles are visible
  188. if (((blockMask[i] >> j) & 1 ) == 0)
  189. tile |= BLOCKED;
  190. if (((visitMask[i] >> j) & 1 ) != 0)
  191. tile |= VISITABLE;
  192. }
  193. }
  194. reader.readUInt16();
  195. ui16 terrMask = reader.readUInt16();
  196. for(TerrainId i = ETerrainId::FIRST_REGULAR_TERRAIN; i < ETerrainId::ORIGINAL_REGULAR_TERRAIN_COUNT; ++i)
  197. {
  198. if (((terrMask >> i.getNum()) & 1 ) != 0)
  199. allowedTerrains.insert(i);
  200. }
  201. //assuming that object can be placed on other land terrains
  202. anyTerrain = allowedTerrains.size() >= 8 && !allowedTerrains.count(ETerrainId::WATER);
  203. id = Obj(reader.readUInt32());
  204. subid = reader.readUInt32();
  205. int type = reader.readUInt8();
  206. printPriority = reader.readUInt8() * 100; // to have some space in future
  207. if (isOnVisitableFromTopList(id, type))
  208. visitDir = 0xff;
  209. else
  210. visitDir = (8|16|32|64|128);
  211. reader.skip(16);
  212. readMsk();
  213. afterLoadFixup();
  214. recalculate();
  215. }
  216. void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain)
  217. {
  218. animationFile = node["animation"].String();
  219. editorAnimationFile = node["editorAnimation"].String();
  220. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  221. if (!visitDirs.empty())
  222. {
  223. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  224. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  225. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  226. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  227. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  228. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  229. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  230. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  231. }
  232. else
  233. visitDir = 0x00;
  234. if(withTerrain && !node["allowedTerrains"].isNull())
  235. {
  236. for(const auto & entry : node["allowedTerrains"].Vector())
  237. {
  238. VLC->modh->identifiers.requestIdentifier("terrain", entry, [this](int32_t identifier){
  239. allowedTerrains.insert(TerrainId(identifier));
  240. });
  241. }
  242. anyTerrain = false;
  243. }
  244. else
  245. {
  246. anyTerrain = true;
  247. }
  248. auto charToTile = [&](const char & ch) -> ui8
  249. {
  250. switch (ch)
  251. {
  252. case ' ' : return 0;
  253. case '0' : return 0;
  254. case 'V' : return VISIBLE;
  255. case 'B' : return VISIBLE | BLOCKED;
  256. case 'H' : return BLOCKED;
  257. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  258. case 'T' : return BLOCKED | VISITABLE;
  259. default:
  260. logGlobal->error("Unrecognized char %s in template mask", ch);
  261. return 0;
  262. }
  263. };
  264. const JsonVector & mask = node["mask"].Vector();
  265. size_t height = mask.size();
  266. size_t width = 0;
  267. for(const auto & line : mask)
  268. vstd::amax(width, line.String().size());
  269. setSize(static_cast<ui32>(width), static_cast<ui32>(height));
  270. for(size_t i = 0; i < mask.size(); i++)
  271. {
  272. const std::string & line = mask[i].String();
  273. for(size_t j = 0; j < line.size(); j++)
  274. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  275. }
  276. printPriority = static_cast<si32>(node["zIndex"].Float());
  277. afterLoadFixup();
  278. recalculate();
  279. }
  280. void ObjectTemplate::writeJson(JsonNode & node, const bool withTerrain) const
  281. {
  282. node["animation"].String() = animationFile;
  283. node["editorAnimation"].String() = editorAnimationFile;
  284. if(visitDir != 0x0 && isVisitable())
  285. {
  286. JsonVector & visitDirs = node["visitableFrom"].Vector();
  287. visitDirs.resize(3);
  288. visitDirs[0].String().resize(3);
  289. visitDirs[1].String().resize(3);
  290. visitDirs[2].String().resize(3);
  291. visitDirs[0].String()[0] = (visitDir & 1) ? '+' : '-';
  292. visitDirs[0].String()[1] = (visitDir & 2) ? '+' : '-';
  293. visitDirs[0].String()[2] = (visitDir & 4) ? '+' : '-';
  294. visitDirs[1].String()[2] = (visitDir & 8) ? '+' : '-';
  295. visitDirs[2].String()[2] = (visitDir & 16) ? '+' : '-';
  296. visitDirs[2].String()[1] = (visitDir & 32) ? '+' : '-';
  297. visitDirs[2].String()[0] = (visitDir & 64) ? '+' : '-';
  298. visitDirs[1].String()[0] = (visitDir & 128) ? '+' : '-';
  299. visitDirs[1].String()[1] = '-';
  300. }
  301. if(withTerrain)
  302. {
  303. //assumed that ROCK and WATER terrains are not included
  304. if(allowedTerrains.size() < (VLC->terrainTypeHandler->objects.size() - 2))
  305. {
  306. JsonVector & data = node["allowedTerrains"].Vector();
  307. for(auto type : allowedTerrains)
  308. {
  309. JsonNode value(JsonNode::JsonType::DATA_STRING);
  310. value.String() = VLC->terrainTypeHandler->getById(type)->getJsonKey();
  311. data.push_back(value);
  312. }
  313. }
  314. }
  315. auto tileToChar = [&](const ui8 & tile) -> char
  316. {
  317. if(tile & VISIBLE)
  318. {
  319. if(tile & BLOCKED)
  320. {
  321. if(tile & VISITABLE)
  322. return 'A';
  323. else
  324. return 'B';
  325. }
  326. else
  327. return 'V';
  328. }
  329. else
  330. {
  331. if(tile & BLOCKED)
  332. {
  333. if(tile & VISITABLE)
  334. return 'T';
  335. else
  336. return 'H';
  337. }
  338. else
  339. return '0';
  340. }
  341. };
  342. size_t height = getHeight();
  343. size_t width = getWidth();
  344. JsonVector & mask = node["mask"].Vector();
  345. for(size_t i=0; i < height; i++)
  346. {
  347. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  348. std::string & line = lineNode.String();
  349. line.resize(width);
  350. for(size_t j=0; j < width; j++)
  351. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  352. mask.push_back(lineNode);
  353. }
  354. if(printPriority != 0)
  355. node["zIndex"].Float() = printPriority;
  356. }
  357. void ObjectTemplate::calculateWidth()
  358. {
  359. //TODO: Use 2D array
  360. for(const auto& row : usedTiles) //copy is expensive
  361. {
  362. width = std::max<ui32>(width, static_cast<ui32>(row.size()));
  363. }
  364. }
  365. void ObjectTemplate::calculateHeight()
  366. {
  367. //TODO: Use 2D array
  368. height = static_cast<ui32>(usedTiles.size());
  369. }
  370. void ObjectTemplate::setSize(ui32 width, ui32 height)
  371. {
  372. usedTiles.resize(height);
  373. for(auto & line : usedTiles)
  374. line.resize(width, 0);
  375. }
  376. void ObjectTemplate::calculateVisitable()
  377. {
  378. for(auto& line : usedTiles)
  379. {
  380. for(auto& tile : line)
  381. {
  382. if (tile & VISITABLE)
  383. {
  384. visitable = true;
  385. return;
  386. }
  387. }
  388. }
  389. visitable = false;
  390. }
  391. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  392. {
  393. if (X < 0 || Y < 0)
  394. return false;
  395. return X < static_cast<si32>(getWidth()) && Y < static_cast<si32>(getHeight());
  396. }
  397. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  398. {
  399. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  400. }
  401. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  402. {
  403. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  404. }
  405. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  406. {
  407. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  408. }
  409. void ObjectTemplate::calculateBlockedOffsets()
  410. {
  411. blockedOffsets.clear();
  412. for(int w = 0; w < static_cast<int>(getWidth()); ++w)
  413. {
  414. for(int h = 0; h < static_cast<int>(getHeight()); ++h)
  415. {
  416. if (isBlockedAt(w, h))
  417. blockedOffsets.insert(int3(-w, -h, 0));
  418. }
  419. }
  420. }
  421. void ObjectTemplate::calculateBlockMapOffset()
  422. {
  423. for(int w = 0; w < static_cast<int>(getWidth()); ++w)
  424. {
  425. for(int h = 0; h < static_cast<int>(getHeight()); ++h)
  426. {
  427. if (isBlockedAt(w, h))
  428. {
  429. blockMapOffset = int3(w, h, 0);
  430. return;
  431. }
  432. }
  433. }
  434. blockMapOffset = int3(0, 0, 0);
  435. }
  436. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  437. {
  438. // visitDir uses format
  439. // 1 2 3
  440. // 8 4
  441. // 7 6 5
  442. //TODO: static? cached?
  443. int dirMap[3][3] =
  444. {
  445. { visitDir & 1, visitDir & 2, visitDir & 4 },
  446. { visitDir & 128, 1 , visitDir & 8 },
  447. { visitDir & 64, visitDir & 32, visitDir & 16 }
  448. };
  449. // map input values to range 0..2
  450. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  451. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  452. return dirMap[dy][dx] != 0;
  453. }
  454. void ObjectTemplate::calculateTopVisibleOffset()
  455. {
  456. for(int y = static_cast<int>(getHeight()) - 1; y >= 0; y--) //Templates start from bottom-right corner
  457. {
  458. for(int x = 0; x < static_cast<int>(getWidth()); x++)
  459. {
  460. if (isVisibleAt(x, y))
  461. {
  462. topVisibleOffset = int3(x, y, 0);
  463. return;
  464. }
  465. }
  466. }
  467. topVisibleOffset = int3(0, 0, 0);
  468. }
  469. void ObjectTemplate::calculateVisitableOffset()
  470. {
  471. for(int y = 0; y < static_cast<int>(getHeight()); y++)
  472. {
  473. for(int x = 0; x < static_cast<int>(getWidth()); x++)
  474. {
  475. if (isVisitableAt(x, y))
  476. {
  477. visitableOffset = int3(x, y, 0);
  478. return;
  479. }
  480. }
  481. }
  482. visitableOffset = int3(0, 0, 0);
  483. }
  484. bool ObjectTemplate::canBePlacedAt(TerrainId terrainID) const
  485. {
  486. if (anyTerrain)
  487. {
  488. const auto & terrain = VLC->terrainTypeHandler->getById(terrainID);
  489. return terrain->isLand() && terrain->isPassable();
  490. }
  491. return vstd::contains(allowedTerrains, terrainID);
  492. }
  493. void ObjectTemplate::recalculate()
  494. {
  495. calculateWidth();
  496. calculateHeight();
  497. calculateVisitable();
  498. //The lines below use width and height
  499. calculateBlockedOffsets();
  500. calculateBlockMapOffset();
  501. calculateVisitableOffset();
  502. calculateTopVisibleOffset();
  503. if (visitable && visitDir == 0)
  504. logMod->warn("Template for %s is visitable but has no visitable directions!", animationFile);
  505. }
  506. VCMI_LIB_NAMESPACE_END