ObjectTemplate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. {
  305. JsonNode value(JsonNode::JsonType::DATA_STRING);
  306. value.String() = VLC->terrainTypeHandler->getById(type)->getJsonKey();
  307. data.push_back(value);
  308. }
  309. }
  310. }
  311. auto tileToChar = [&](const ui8 & tile) -> char
  312. {
  313. if(tile & VISIBLE)
  314. {
  315. if(tile & BLOCKED)
  316. {
  317. if(tile & VISITABLE)
  318. return 'A';
  319. else
  320. return 'B';
  321. }
  322. else
  323. return 'V';
  324. }
  325. else
  326. {
  327. if(tile & BLOCKED)
  328. {
  329. if(tile & VISITABLE)
  330. return 'T';
  331. else
  332. return 'H';
  333. }
  334. else
  335. return '0';
  336. }
  337. };
  338. size_t height = getHeight();
  339. size_t width = getWidth();
  340. JsonVector & mask = node["mask"].Vector();
  341. for(size_t i=0; i < height; i++)
  342. {
  343. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  344. std::string & line = lineNode.String();
  345. line.resize(width);
  346. for(size_t j=0; j < width; j++)
  347. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  348. mask.push_back(lineNode);
  349. }
  350. if(printPriority != 0)
  351. node["zIndex"].Float() = printPriority;
  352. }
  353. void ObjectTemplate::calculateWidth()
  354. {
  355. //TODO: Use 2D array
  356. for(const auto& row : usedTiles) //copy is expensive
  357. {
  358. width = std::max<ui32>(width, static_cast<ui32>(row.size()));
  359. }
  360. }
  361. void ObjectTemplate::calculateHeight()
  362. {
  363. //TODO: Use 2D array
  364. height = static_cast<ui32>(usedTiles.size());
  365. }
  366. void ObjectTemplate::setSize(ui32 width, ui32 height)
  367. {
  368. usedTiles.resize(height);
  369. for(auto & line : usedTiles)
  370. line.resize(width, 0);
  371. }
  372. void ObjectTemplate::calculateVisitable()
  373. {
  374. for(auto& line : usedTiles)
  375. {
  376. for(auto& tile : line)
  377. {
  378. if (tile & VISITABLE)
  379. {
  380. visitable = true;
  381. return;
  382. }
  383. }
  384. }
  385. visitable = false;
  386. }
  387. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  388. {
  389. if (X < 0 || Y < 0)
  390. return false;
  391. return X < static_cast<si32>(getWidth()) && Y < static_cast<si32>(getHeight());
  392. }
  393. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  394. {
  395. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  396. }
  397. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  398. {
  399. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  400. }
  401. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  402. {
  403. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  404. }
  405. void ObjectTemplate::calculateBlockedOffsets()
  406. {
  407. blockedOffsets.clear();
  408. for(int w = 0; w < static_cast<int>(getWidth()); ++w)
  409. {
  410. for(int h = 0; h < static_cast<int>(getHeight()); ++h)
  411. {
  412. if (isBlockedAt(w, h))
  413. blockedOffsets.insert(int3(-w, -h, 0));
  414. }
  415. }
  416. }
  417. void ObjectTemplate::calculateBlockMapOffset()
  418. {
  419. for(int w = 0; w < static_cast<int>(getWidth()); ++w)
  420. {
  421. for(int h = 0; h < static_cast<int>(getHeight()); ++h)
  422. {
  423. if (isBlockedAt(w, h))
  424. {
  425. blockMapOffset = int3(w, h, 0);
  426. return;
  427. }
  428. }
  429. }
  430. blockMapOffset = int3(0, 0, 0);
  431. }
  432. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  433. {
  434. // visitDir uses format
  435. // 1 2 3
  436. // 8 4
  437. // 7 6 5
  438. //TODO: static? cached?
  439. int dirMap[3][3] =
  440. {
  441. { visitDir & 1, visitDir & 2, visitDir & 4 },
  442. { visitDir & 128, 1 , visitDir & 8 },
  443. { visitDir & 64, visitDir & 32, visitDir & 16 }
  444. };
  445. // map input values to range 0..2
  446. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  447. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  448. return dirMap[dy][dx] != 0;
  449. }
  450. void ObjectTemplate::calculateTopVisibleOffset()
  451. {
  452. for(int y = static_cast<int>(getHeight()) - 1; y >= 0; y--) //Templates start from bottom-right corner
  453. {
  454. for(int x = 0; x < static_cast<int>(getWidth()); x++)
  455. {
  456. if (isVisibleAt(x, y))
  457. {
  458. topVisibleOffset = int3(x, y, 0);
  459. return;
  460. }
  461. }
  462. }
  463. topVisibleOffset = int3(0, 0, 0);
  464. }
  465. void ObjectTemplate::calculateVisitableOffset()
  466. {
  467. for(int y = 0; y < static_cast<int>(getHeight()); y++)
  468. {
  469. for(int x = 0; x < static_cast<int>(getWidth()); x++)
  470. {
  471. if (isVisitableAt(x, y))
  472. {
  473. visitableOffset = int3(x, y, 0);
  474. return;
  475. }
  476. }
  477. }
  478. visitableOffset = int3(0, 0, 0);
  479. }
  480. bool ObjectTemplate::canBePlacedAt(TerrainId terrainID) const
  481. {
  482. if (anyLandTerrain)
  483. {
  484. const auto & terrain = VLC->terrainTypeHandler->getById(terrainID);
  485. return terrain->isLand() && terrain->isPassable();
  486. }
  487. return vstd::contains(allowedTerrains, terrainID);
  488. }
  489. void ObjectTemplate::recalculate()
  490. {
  491. calculateWidth();
  492. calculateHeight();
  493. calculateVisitable();
  494. //The lines below use width and height
  495. calculateBlockedOffsets();
  496. calculateBlockMapOffset();
  497. calculateVisitableOffset();
  498. calculateTopVisibleOffset();
  499. if (visitable && visitDir == 0)
  500. logMod->warn("Template for %s is visitable but has no visitable directions!", animationFile.getOriginalName());
  501. }
  502. VCMI_LIB_NAMESPACE_END