ObjectTemplate.cpp 14 KB

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