ObjectTemplate.cpp 13 KB

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