ObjectTemplate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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 "CObjectClassesHandler.h"
  12. #include "../filesystem/Filesystem.h"
  13. #include "../filesystem/CBinaryReader.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../GameConstants.h"
  16. #include "../StringConstants.h"
  17. #include "../CGeneralTextHandler.h"
  18. #include "CObjectHandler.h"
  19. #include "../CModHandler.h"
  20. #include "../JsonNode.h"
  21. #include "../Terrain.h"
  22. #include "CRewardableConstructor.h"
  23. static bool isOnVisitableFromTopList(int 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() == Terrain::ROCK - 1); // all terrains but rock
  140. for(TTerrainId i = Terrain::FIRST_REGULAR_TERRAIN; i < Terrain::ROCK; i++)
  141. {
  142. if (terrStr[8-i] == '1')
  143. allowedTerrains.insert(i);
  144. }
  145. //assuming that object can be placed on other land terrains
  146. if(allowedTerrains.size() >= 8 && !allowedTerrains.count(Terrain::WATER))
  147. {
  148. for(const auto * terrain : VLC->terrainTypeHandler->terrains())
  149. {
  150. if(terrain->isLand() && terrain->isPassable())
  151. allowedTerrains.insert(terrain->id);
  152. }
  153. }
  154. id = Obj(boost::lexical_cast<int>(strings[5]));
  155. subid = boost::lexical_cast<int>(strings[6]);
  156. int type = boost::lexical_cast<int>(strings[7]);
  157. printPriority = boost::lexical_cast<int>(strings[8]) * 100; // to have some space in future
  158. if (isOnVisitableFromTopList(id, type))
  159. visitDir = 0xff;
  160. else
  161. visitDir = (8|16|32|64|128);
  162. readMsk();
  163. recalculate();
  164. }
  165. void ObjectTemplate::readMsk()
  166. {
  167. ResourceID resID("SPRITES/" + animationFile, EResType::MASK);
  168. if (CResourceHandler::get()->existsResource(resID))
  169. {
  170. auto msk = CResourceHandler::get()->load(resID)->readAll();
  171. setSize(msk.first.get()[0], msk.first.get()[1]);
  172. }
  173. else //maximum possible size of H3 object //TODO: remove hardcode and move this data into modding system
  174. {
  175. setSize(8, 6);
  176. }
  177. }
  178. void ObjectTemplate::readMap(CBinaryReader & reader)
  179. {
  180. animationFile = reader.readString();
  181. setSize(8, 6);
  182. ui8 blockMask[6];
  183. ui8 visitMask[6];
  184. for(auto & byte : blockMask)
  185. byte = reader.readUInt8();
  186. for(auto & byte : visitMask)
  187. byte = reader.readUInt8();
  188. for(size_t i = 0; i < 6; i++) // 6 rows
  189. {
  190. for(size_t j = 0; j < 8; j++) // 8 columns
  191. {
  192. auto & tile = usedTiles[5 - i][7 - j];
  193. tile |= VISIBLE; // assume that all tiles are visible
  194. if (((blockMask[i] >> j) & 1 ) == 0)
  195. tile |= BLOCKED;
  196. if (((visitMask[i] >> j) & 1 ) != 0)
  197. tile |= VISITABLE;
  198. }
  199. }
  200. reader.readUInt16();
  201. ui16 terrMask = reader.readUInt16();
  202. for(size_t i = Terrain::FIRST_REGULAR_TERRAIN; i < Terrain::ROCK; i++)
  203. {
  204. if (((terrMask >> i) & 1 ) != 0)
  205. allowedTerrains.insert(i);
  206. }
  207. //assuming that object can be placed on other land terrains
  208. if(allowedTerrains.size() >= 8 && !allowedTerrains.count(Terrain::WATER))
  209. {
  210. for(const auto * terrain : VLC->terrainTypeHandler->terrains())
  211. {
  212. if(terrain->isLand() && terrain->isPassable())
  213. allowedTerrains.insert(terrain->id);
  214. }
  215. }
  216. id = Obj(reader.readUInt32());
  217. subid = reader.readUInt32();
  218. int type = reader.readUInt8();
  219. printPriority = reader.readUInt8() * 100; // to have some space in future
  220. if (isOnVisitableFromTopList(id, type))
  221. visitDir = 0xff;
  222. else
  223. visitDir = (8|16|32|64|128);
  224. reader.skip(16);
  225. readMsk();
  226. afterLoadFixup();
  227. recalculate();
  228. }
  229. void ObjectTemplate::readJson(const JsonNode &node, const bool withTerrain)
  230. {
  231. animationFile = node["animation"].String();
  232. editorAnimationFile = node["editorAnimation"].String();
  233. const JsonVector & visitDirs = node["visitableFrom"].Vector();
  234. if (!visitDirs.empty())
  235. {
  236. if (visitDirs[0].String()[0] == '+') visitDir |= 1;
  237. if (visitDirs[0].String()[1] == '+') visitDir |= 2;
  238. if (visitDirs[0].String()[2] == '+') visitDir |= 4;
  239. if (visitDirs[1].String()[2] == '+') visitDir |= 8;
  240. if (visitDirs[2].String()[2] == '+') visitDir |= 16;
  241. if (visitDirs[2].String()[1] == '+') visitDir |= 32;
  242. if (visitDirs[2].String()[0] == '+') visitDir |= 64;
  243. if (visitDirs[1].String()[0] == '+') visitDir |= 128;
  244. }
  245. else
  246. visitDir = 0x00;
  247. if(withTerrain && !node["allowedTerrains"].isNull())
  248. {
  249. for(auto& entry : node["allowedTerrains"].Vector())
  250. allowedTerrains.insert(VLC->terrainTypeHandler->getInfoByName(entry.String())->id);
  251. }
  252. else
  253. {
  254. for(const auto* terrain : VLC->terrainTypeHandler->terrains())
  255. {
  256. if(!terrain->isPassable() || terrain->isWater())
  257. continue;
  258. allowedTerrains.insert(terrain->id);
  259. }
  260. }
  261. if(withTerrain && allowedTerrains.empty())
  262. logGlobal->warn("Loaded template without allowed terrains!");
  263. auto charToTile = [&](const char & ch) -> ui8
  264. {
  265. switch (ch)
  266. {
  267. case ' ' : return 0;
  268. case '0' : return 0;
  269. case 'V' : return VISIBLE;
  270. case 'B' : return VISIBLE | BLOCKED;
  271. case 'H' : return BLOCKED;
  272. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  273. case 'T' : return BLOCKED | VISITABLE;
  274. default:
  275. logGlobal->error("Unrecognized char %s in template mask", ch);
  276. return 0;
  277. }
  278. };
  279. const JsonVector & mask = node["mask"].Vector();
  280. size_t height = mask.size();
  281. size_t width = 0;
  282. for(auto & line : mask)
  283. vstd::amax(width, line.String().size());
  284. setSize((ui32)width, (ui32)height);
  285. for(size_t i = 0; i < mask.size(); i++)
  286. {
  287. const std::string & line = mask[i].String();
  288. for(size_t j = 0; j < line.size(); j++)
  289. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  290. }
  291. printPriority = static_cast<si32>(node["zIndex"].Float());
  292. afterLoadFixup();
  293. recalculate();
  294. }
  295. void ObjectTemplate::writeJson(JsonNode & node, const bool withTerrain) const
  296. {
  297. node["animation"].String() = animationFile;
  298. node["editorAnimation"].String() = editorAnimationFile;
  299. if(visitDir != 0x0 && isVisitable())
  300. {
  301. JsonVector & visitDirs = node["visitableFrom"].Vector();
  302. visitDirs.resize(3);
  303. visitDirs[0].String().resize(3);
  304. visitDirs[1].String().resize(3);
  305. visitDirs[2].String().resize(3);
  306. visitDirs[0].String()[0] = (visitDir & 1) ? '+' : '-';
  307. visitDirs[0].String()[1] = (visitDir & 2) ? '+' : '-';
  308. visitDirs[0].String()[2] = (visitDir & 4) ? '+' : '-';
  309. visitDirs[1].String()[2] = (visitDir & 8) ? '+' : '-';
  310. visitDirs[2].String()[2] = (visitDir & 16) ? '+' : '-';
  311. visitDirs[2].String()[1] = (visitDir & 32) ? '+' : '-';
  312. visitDirs[2].String()[0] = (visitDir & 64) ? '+' : '-';
  313. visitDirs[1].String()[0] = (visitDir & 128) ? '+' : '-';
  314. visitDirs[1].String()[1] = '-';
  315. }
  316. if(withTerrain)
  317. {
  318. //assumed that ROCK and WATER terrains are not included
  319. if(allowedTerrains.size() < (VLC->terrainTypeHandler->terrains().size() - 2))
  320. {
  321. JsonVector & data = node["allowedTerrains"].Vector();
  322. for(auto type : allowedTerrains)
  323. {
  324. JsonNode value(JsonNode::JsonType::DATA_STRING);
  325. value.String() = type;
  326. data.push_back(value);
  327. }
  328. }
  329. }
  330. auto tileToChar = [&](const ui8 & tile) -> char
  331. {
  332. if(tile & VISIBLE)
  333. {
  334. if(tile & BLOCKED)
  335. {
  336. if(tile & VISITABLE)
  337. return 'A';
  338. else
  339. return 'B';
  340. }
  341. else
  342. return 'V';
  343. }
  344. else
  345. {
  346. if(tile & BLOCKED)
  347. {
  348. if(tile & VISITABLE)
  349. return 'T';
  350. else
  351. return 'H';
  352. }
  353. else
  354. return '0';
  355. }
  356. };
  357. size_t height = getHeight();
  358. size_t width = getWidth();
  359. JsonVector & mask = node["mask"].Vector();
  360. for(size_t i=0; i < height; i++)
  361. {
  362. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  363. std::string & line = lineNode.String();
  364. line.resize(width);
  365. for(size_t j=0; j < width; j++)
  366. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  367. mask.push_back(lineNode);
  368. }
  369. if(printPriority != 0)
  370. node["zIndex"].Float() = printPriority;
  371. }
  372. void ObjectTemplate::calculateWidth()
  373. {
  374. //TODO: Use 2D array
  375. for(const auto& row : usedTiles) //copy is expensive
  376. {
  377. width = std::max<ui32>(width, (ui32)row.size());
  378. }
  379. }
  380. void ObjectTemplate::calculateHeight()
  381. {
  382. //TODO: Use 2D array
  383. height = static_cast<ui32>(usedTiles.size());
  384. }
  385. void ObjectTemplate::setSize(ui32 width, ui32 height)
  386. {
  387. usedTiles.resize(height);
  388. for(auto & line : usedTiles)
  389. line.resize(width, 0);
  390. }
  391. void ObjectTemplate::calculateVsitable()
  392. {
  393. for(auto& line : usedTiles)
  394. {
  395. for(auto& tile : line)
  396. {
  397. if (tile & VISITABLE)
  398. {
  399. visitable = true;
  400. return;
  401. }
  402. }
  403. }
  404. visitable = false;
  405. }
  406. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  407. {
  408. if (X < 0 || Y < 0)
  409. return false;
  410. return !(X >= (si32)getWidth() || Y >= (si32)getHeight());
  411. }
  412. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  413. {
  414. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  415. }
  416. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  417. {
  418. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  419. }
  420. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  421. {
  422. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  423. }
  424. void ObjectTemplate::calculateBlockedOffsets()
  425. {
  426. blockedOffsets.clear();
  427. for(int w = 0; w < (int)getWidth(); ++w)
  428. {
  429. for(int h = 0; h < (int)getHeight(); ++h)
  430. {
  431. if (isBlockedAt(w, h))
  432. blockedOffsets.insert(int3(-w, -h, 0));
  433. }
  434. }
  435. }
  436. void ObjectTemplate::calculateBlockMapOffset()
  437. {
  438. for(int w = 0; w < (int)getWidth(); ++w)
  439. {
  440. for(int h = 0; h < (int)getHeight(); ++h)
  441. {
  442. if (isBlockedAt(w, h))
  443. {
  444. blockMapOffset = int3(w, h, 0);
  445. return;
  446. }
  447. }
  448. }
  449. blockMapOffset = int3(0, 0, 0);
  450. }
  451. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  452. {
  453. // visitDir uses format
  454. // 1 2 3
  455. // 8 4
  456. // 7 6 5
  457. //TODO: static? cached?
  458. int dirMap[3][3] =
  459. {
  460. { visitDir & 1, visitDir & 2, visitDir & 4 },
  461. { visitDir & 128, 1 , visitDir & 8 },
  462. { visitDir & 64, visitDir & 32, visitDir & 16 }
  463. };
  464. // map input values to range 0..2
  465. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  466. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  467. return dirMap[dy][dx] != 0;
  468. }
  469. void ObjectTemplate::calculateVisitableOffset()
  470. {
  471. for(int y = 0; y < (int)getHeight(); y++)
  472. {
  473. for(int x = 0; x < (int)getWidth(); x++)
  474. {
  475. if (isVisitableAt(x, y))
  476. {
  477. visitableOffset = int3(x, y, 0);
  478. return;
  479. }
  480. }
  481. }
  482. visitableOffset = int3(0, 0, 0);
  483. }
  484. bool ObjectTemplate::canBePlacedAt(TTerrainId terrain) const
  485. {
  486. return vstd::contains(allowedTerrains, terrain);
  487. }
  488. void ObjectTemplate::recalculate()
  489. {
  490. calculateWidth();
  491. calculateHeight();
  492. calculateVsitable();
  493. //The lines below use width and height
  494. calculateBlockedOffsets();
  495. calculateBlockMapOffset();
  496. calculateVisitableOffset();
  497. }