2
0

ObjectTemplate.cpp 14 KB

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