ObjectTemplate.cpp 14 KB

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