ObjectTemplate.cpp 13 KB

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