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 "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(ETerrainId::ROCK).getNum()); // all terrains but rock - counting from 0
  141. for(TerrainId i = TerrainId(0); i < ETerrainId::ROCK; ++i)
  142. {
  143. if (terrStr[8-i.getNum()] == '1')
  144. allowedTerrains.insert(i);
  145. }
  146. //assuming that object can be placed on other land terrains
  147. if(allowedTerrains.size() >= 8 && !allowedTerrains.count(ETerrainId::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 = ETerrainId::FIRST_REGULAR_TERRAIN; i < ETerrainId::ORIGINAL_TERRAIN_COUNT; ++i)
  204. {
  205. if (((terrMask >> i.getNum()) & 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(ETerrainId::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. VLC->modh->identifiers.requestIdentifier("terrain", entry, [this](int32_t identifier){
  253. allowedTerrains.insert(TerrainId(identifier));
  254. });
  255. }
  256. }
  257. else
  258. {
  259. for(const auto & terrain : VLC->terrainTypeHandler->objects)
  260. {
  261. if(!terrain->isPassable() || terrain->isWater())
  262. continue;
  263. allowedTerrains.insert(terrain->id);
  264. }
  265. }
  266. if(withTerrain && allowedTerrains.empty())
  267. logGlobal->warn("Loaded template %s without allowed terrains!", animationFile);
  268. auto charToTile = [&](const char & ch) -> ui8
  269. {
  270. switch (ch)
  271. {
  272. case ' ' : return 0;
  273. case '0' : return 0;
  274. case 'V' : return VISIBLE;
  275. case 'B' : return VISIBLE | BLOCKED;
  276. case 'H' : return BLOCKED;
  277. case 'A' : return VISIBLE | BLOCKED | VISITABLE;
  278. case 'T' : return BLOCKED | VISITABLE;
  279. default:
  280. logGlobal->error("Unrecognized char %s in template mask", ch);
  281. return 0;
  282. }
  283. };
  284. const JsonVector & mask = node["mask"].Vector();
  285. size_t height = mask.size();
  286. size_t width = 0;
  287. for(auto & line : mask)
  288. vstd::amax(width, line.String().size());
  289. setSize((ui32)width, (ui32)height);
  290. for(size_t i = 0; i < mask.size(); i++)
  291. {
  292. const std::string & line = mask[i].String();
  293. for(size_t j = 0; j < line.size(); j++)
  294. usedTiles[mask.size() - 1 - i][line.size() - 1 - j] = charToTile(line[j]);
  295. }
  296. printPriority = static_cast<si32>(node["zIndex"].Float());
  297. afterLoadFixup();
  298. recalculate();
  299. }
  300. void ObjectTemplate::writeJson(JsonNode & node, const bool withTerrain) const
  301. {
  302. node["animation"].String() = animationFile;
  303. node["editorAnimation"].String() = editorAnimationFile;
  304. if(visitDir != 0x0 && isVisitable())
  305. {
  306. JsonVector & visitDirs = node["visitableFrom"].Vector();
  307. visitDirs.resize(3);
  308. visitDirs[0].String().resize(3);
  309. visitDirs[1].String().resize(3);
  310. visitDirs[2].String().resize(3);
  311. visitDirs[0].String()[0] = (visitDir & 1) ? '+' : '-';
  312. visitDirs[0].String()[1] = (visitDir & 2) ? '+' : '-';
  313. visitDirs[0].String()[2] = (visitDir & 4) ? '+' : '-';
  314. visitDirs[1].String()[2] = (visitDir & 8) ? '+' : '-';
  315. visitDirs[2].String()[2] = (visitDir & 16) ? '+' : '-';
  316. visitDirs[2].String()[1] = (visitDir & 32) ? '+' : '-';
  317. visitDirs[2].String()[0] = (visitDir & 64) ? '+' : '-';
  318. visitDirs[1].String()[0] = (visitDir & 128) ? '+' : '-';
  319. visitDirs[1].String()[1] = '-';
  320. }
  321. if(withTerrain)
  322. {
  323. //assumed that ROCK and WATER terrains are not included
  324. if(allowedTerrains.size() < (VLC->terrainTypeHandler->objects.size() - 2))
  325. {
  326. JsonVector & data = node["allowedTerrains"].Vector();
  327. for(auto type : allowedTerrains)
  328. {
  329. JsonNode value(JsonNode::JsonType::DATA_STRING);
  330. value.String() = VLC->terrainTypeHandler->getById(type)->name;
  331. data.push_back(value);
  332. }
  333. }
  334. }
  335. auto tileToChar = [&](const ui8 & tile) -> char
  336. {
  337. if(tile & VISIBLE)
  338. {
  339. if(tile & BLOCKED)
  340. {
  341. if(tile & VISITABLE)
  342. return 'A';
  343. else
  344. return 'B';
  345. }
  346. else
  347. return 'V';
  348. }
  349. else
  350. {
  351. if(tile & BLOCKED)
  352. {
  353. if(tile & VISITABLE)
  354. return 'T';
  355. else
  356. return 'H';
  357. }
  358. else
  359. return '0';
  360. }
  361. };
  362. size_t height = getHeight();
  363. size_t width = getWidth();
  364. JsonVector & mask = node["mask"].Vector();
  365. for(size_t i=0; i < height; i++)
  366. {
  367. JsonNode lineNode(JsonNode::JsonType::DATA_STRING);
  368. std::string & line = lineNode.String();
  369. line.resize(width);
  370. for(size_t j=0; j < width; j++)
  371. line[j] = tileToChar(usedTiles[height - 1 - i][width - 1 - j]);
  372. mask.push_back(lineNode);
  373. }
  374. if(printPriority != 0)
  375. node["zIndex"].Float() = printPriority;
  376. }
  377. void ObjectTemplate::calculateWidth()
  378. {
  379. //TODO: Use 2D array
  380. for(const auto& row : usedTiles) //copy is expensive
  381. {
  382. width = std::max<ui32>(width, (ui32)row.size());
  383. }
  384. }
  385. void ObjectTemplate::calculateHeight()
  386. {
  387. //TODO: Use 2D array
  388. height = static_cast<ui32>(usedTiles.size());
  389. }
  390. void ObjectTemplate::setSize(ui32 width, ui32 height)
  391. {
  392. usedTiles.resize(height);
  393. for(auto & line : usedTiles)
  394. line.resize(width, 0);
  395. }
  396. void ObjectTemplate::calculateVsitable()
  397. {
  398. for(auto& line : usedTiles)
  399. {
  400. for(auto& tile : line)
  401. {
  402. if (tile & VISITABLE)
  403. {
  404. visitable = true;
  405. return;
  406. }
  407. }
  408. }
  409. visitable = false;
  410. }
  411. bool ObjectTemplate::isWithin(si32 X, si32 Y) const
  412. {
  413. if (X < 0 || Y < 0)
  414. return false;
  415. return !(X >= (si32)getWidth() || Y >= (si32)getHeight());
  416. }
  417. bool ObjectTemplate::isVisitableAt(si32 X, si32 Y) const
  418. {
  419. return isWithin(X, Y) && usedTiles[Y][X] & VISITABLE;
  420. }
  421. bool ObjectTemplate::isVisibleAt(si32 X, si32 Y) const
  422. {
  423. return isWithin(X, Y) && usedTiles[Y][X] & VISIBLE;
  424. }
  425. bool ObjectTemplate::isBlockedAt(si32 X, si32 Y) const
  426. {
  427. return isWithin(X, Y) && usedTiles[Y][X] & BLOCKED;
  428. }
  429. void ObjectTemplate::calculateBlockedOffsets()
  430. {
  431. blockedOffsets.clear();
  432. for(int w = 0; w < (int)getWidth(); ++w)
  433. {
  434. for(int h = 0; h < (int)getHeight(); ++h)
  435. {
  436. if (isBlockedAt(w, h))
  437. blockedOffsets.insert(int3(-w, -h, 0));
  438. }
  439. }
  440. }
  441. void ObjectTemplate::calculateBlockMapOffset()
  442. {
  443. for(int w = 0; w < (int)getWidth(); ++w)
  444. {
  445. for(int h = 0; h < (int)getHeight(); ++h)
  446. {
  447. if (isBlockedAt(w, h))
  448. {
  449. blockMapOffset = int3(w, h, 0);
  450. return;
  451. }
  452. }
  453. }
  454. blockMapOffset = int3(0, 0, 0);
  455. }
  456. bool ObjectTemplate::isVisitableFrom(si8 X, si8 Y) const
  457. {
  458. // visitDir uses format
  459. // 1 2 3
  460. // 8 4
  461. // 7 6 5
  462. //TODO: static? cached?
  463. int dirMap[3][3] =
  464. {
  465. { visitDir & 1, visitDir & 2, visitDir & 4 },
  466. { visitDir & 128, 1 , visitDir & 8 },
  467. { visitDir & 64, visitDir & 32, visitDir & 16 }
  468. };
  469. // map input values to range 0..2
  470. int dx = X < 0 ? 0 : X == 0 ? 1 : 2;
  471. int dy = Y < 0 ? 0 : Y == 0 ? 1 : 2;
  472. return dirMap[dy][dx] != 0;
  473. }
  474. void ObjectTemplate::calculateVisitableOffset()
  475. {
  476. for(int y = 0; y < (int)getHeight(); y++)
  477. {
  478. for(int x = 0; x < (int)getWidth(); x++)
  479. {
  480. if (isVisitableAt(x, y))
  481. {
  482. visitableOffset = int3(x, y, 0);
  483. return;
  484. }
  485. }
  486. }
  487. visitableOffset = int3(0, 0, 0);
  488. }
  489. bool ObjectTemplate::canBePlacedAt(TerrainId terrain) const
  490. {
  491. return vstd::contains(allowedTerrains, terrain);
  492. }
  493. void ObjectTemplate::recalculate()
  494. {
  495. calculateWidth();
  496. calculateHeight();
  497. calculateVsitable();
  498. //The lines below use width and height
  499. calculateBlockedOffsets();
  500. calculateBlockMapOffset();
  501. calculateVisitableOffset();
  502. }
  503. VCMI_LIB_NAMESPACE_END