CAnimation.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. * CAnimation.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 "CAnimation.h"
  12. #include "CDefFile.h"
  13. #include "Graphics.h"
  14. #include "../../lib/filesystem/Filesystem.h"
  15. #include "../../lib/json/JsonUtils.h"
  16. #include "../renderSDL/SDLImage.h"
  17. std::shared_ptr<IImage> CAnimation::getFromExtraDef(std::string filename)
  18. {
  19. size_t pos = filename.find(':');
  20. if (pos == -1)
  21. return nullptr;
  22. CAnimation anim(AnimationPath::builtinTODO(filename.substr(0, pos)));
  23. pos++;
  24. size_t frame = atoi(filename.c_str()+pos);
  25. size_t group = 0;
  26. pos = filename.find(':', pos);
  27. if (pos != -1)
  28. {
  29. pos++;
  30. group = frame;
  31. frame = atoi(filename.c_str()+pos);
  32. }
  33. anim.load(frame ,group);
  34. auto ret = anim.images[group][frame];
  35. anim.images.clear();
  36. return ret;
  37. }
  38. bool CAnimation::loadFrame(size_t frame, size_t group)
  39. {
  40. if(size(group) <= frame)
  41. {
  42. printError(frame, group, "LoadFrame");
  43. return false;
  44. }
  45. auto image = getImage(frame, group, false);
  46. if(image)
  47. {
  48. return true;
  49. }
  50. //try to get image from def
  51. if(source[group][frame].getType() == JsonNode::JsonType::DATA_NULL)
  52. {
  53. if(defFile)
  54. {
  55. auto frameList = defFile->getEntries();
  56. if(vstd::contains(frameList, group) && frameList.at(group) > frame) // frame is present
  57. {
  58. images[group][frame] = std::make_shared<SDLImage>(defFile.get(), frame, group);
  59. return true;
  60. }
  61. }
  62. // still here? image is missing
  63. printError(frame, group, "LoadFrame");
  64. images[group][frame] = std::make_shared<SDLImage>(ImagePath::builtin("DEFAULT"), EImageBlitMode::ALPHA);
  65. }
  66. else //load from separate file
  67. {
  68. auto img = getFromExtraDef(source[group][frame]["file"].String());
  69. if(!img)
  70. img = std::make_shared<SDLImage>(source[group][frame], EImageBlitMode::ALPHA);
  71. images[group][frame] = img;
  72. return true;
  73. }
  74. return false;
  75. }
  76. bool CAnimation::unloadFrame(size_t frame, size_t group)
  77. {
  78. auto image = getImage(frame, group, false);
  79. if(image)
  80. {
  81. images[group].erase(frame);
  82. if(images[group].empty())
  83. images.erase(group);
  84. return true;
  85. }
  86. return false;
  87. }
  88. void CAnimation::initFromJson(const JsonNode & config)
  89. {
  90. std::string basepath;
  91. basepath = config["basepath"].String();
  92. JsonNode base;
  93. base["margins"] = config["margins"];
  94. base["width"] = config["width"];
  95. base["height"] = config["height"];
  96. for(const JsonNode & group : config["sequences"].Vector())
  97. {
  98. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  99. source[groupID].clear();
  100. for(const JsonNode & frame : group["frames"].Vector())
  101. {
  102. JsonNode toAdd;
  103. JsonUtils::inherit(toAdd, base);
  104. toAdd["file"].String() = basepath + frame.String();
  105. source[groupID].push_back(toAdd);
  106. }
  107. }
  108. for(const JsonNode & node : config["images"].Vector())
  109. {
  110. size_t group = node["group"].Integer();
  111. size_t frame = node["frame"].Integer();
  112. if (source[group].size() <= frame)
  113. source[group].resize(frame+1);
  114. JsonNode toAdd;
  115. JsonUtils::inherit(toAdd, base);
  116. toAdd["file"].String() = basepath + node["file"].String();
  117. source[group][frame] = toAdd;
  118. }
  119. }
  120. void CAnimation::exportBitmaps(const boost::filesystem::path& path) const
  121. {
  122. if(images.empty())
  123. {
  124. logGlobal->error("Nothing to export, animation is empty");
  125. return;
  126. }
  127. boost::filesystem::path actualPath = path / "SPRITES" / name.getName();
  128. boost::filesystem::create_directories(actualPath);
  129. size_t counter = 0;
  130. for(const auto & groupPair : images)
  131. {
  132. size_t group = groupPair.first;
  133. for(const auto & imagePair : groupPair.second)
  134. {
  135. size_t frame = imagePair.first;
  136. const auto img = imagePair.second;
  137. boost::format fmt("%d_%d.bmp");
  138. fmt % group % frame;
  139. img->exportBitmap(actualPath / fmt.str());
  140. counter++;
  141. }
  142. }
  143. logGlobal->info("Exported %d frames to %s", counter, actualPath.string());
  144. }
  145. void CAnimation::init()
  146. {
  147. if(defFile)
  148. {
  149. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  150. for (auto & defEntry : defEntries)
  151. source[defEntry.first].resize(defEntry.second);
  152. }
  153. if (vstd::contains(graphics->imageLists, name.getName()))
  154. initFromJson(graphics->imageLists[name.getName()]);
  155. auto jsonResource = name.toType<EResType::JSON>();
  156. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  157. for(auto & loader : configList)
  158. {
  159. auto stream = loader->load(jsonResource);
  160. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  161. stream->read(textData.get(), stream->getSize());
  162. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize());
  163. initFromJson(config);
  164. }
  165. }
  166. void CAnimation::printError(size_t frame, size_t group, std::string type) const
  167. {
  168. logGlobal->error("%s error: Request for frame not present in CAnimation! File name: %s, Group: %d, Frame: %d", type, name.getOriginalName(), group, frame);
  169. }
  170. CAnimation::CAnimation(const AnimationPath & Name):
  171. name(boost::starts_with(Name.getName(), "SPRITES") ? Name : Name.addPrefix("SPRITES/")),
  172. preloaded(false)
  173. {
  174. if(CResourceHandler::get()->existsResource(name))
  175. {
  176. try
  177. {
  178. defFile = std::make_shared<CDefFile>(name);
  179. }
  180. catch ( const std::runtime_error & e)
  181. {
  182. logAnim->error("Def file %s failed to load! Reason: %s", Name.getOriginalName(), e.what());
  183. }
  184. }
  185. init();
  186. if(source.empty())
  187. logAnim->error("Animation %s failed to load", Name.getOriginalName());
  188. }
  189. CAnimation::CAnimation():
  190. preloaded(false)
  191. {
  192. init();
  193. }
  194. CAnimation::~CAnimation() = default;
  195. void CAnimation::duplicateImage(const size_t sourceGroup, const size_t sourceFrame, const size_t targetGroup)
  196. {
  197. if(!source.count(sourceGroup))
  198. {
  199. logAnim->error("Group %d missing in %s", sourceGroup, name.getName());
  200. return;
  201. }
  202. if(source[sourceGroup].size() <= sourceFrame)
  203. {
  204. logAnim->error("Frame [%d %d] missing in %s", sourceGroup, sourceFrame, name.getName());
  205. return;
  206. }
  207. //todo: clone actual loaded Image object
  208. JsonNode clone(source[sourceGroup][sourceFrame]);
  209. if(clone.getType() == JsonNode::JsonType::DATA_NULL)
  210. {
  211. std::string temp = name.getName()+":"+std::to_string(sourceGroup)+":"+std::to_string(sourceFrame);
  212. clone["file"].String() = temp;
  213. }
  214. source[targetGroup].push_back(clone);
  215. size_t index = source[targetGroup].size() - 1;
  216. if(preloaded)
  217. load(index, targetGroup);
  218. }
  219. void CAnimation::setCustom(std::string filename, size_t frame, size_t group)
  220. {
  221. if (source[group].size() <= frame)
  222. source[group].resize(frame+1);
  223. source[group][frame]["file"].String() = filename;
  224. //FIXME: update image if already loaded
  225. }
  226. std::shared_ptr<IImage> CAnimation::getImage(size_t frame, size_t group, bool verbose) const
  227. {
  228. auto groupIter = images.find(group);
  229. if (groupIter != images.end())
  230. {
  231. auto imageIter = groupIter->second.find(frame);
  232. if (imageIter != groupIter->second.end())
  233. return imageIter->second;
  234. }
  235. if (verbose)
  236. printError(frame, group, "GetImage");
  237. return nullptr;
  238. }
  239. void CAnimation::load()
  240. {
  241. for (auto & elem : source)
  242. for (size_t image=0; image < elem.second.size(); image++)
  243. loadFrame(image, elem.first);
  244. }
  245. void CAnimation::unload()
  246. {
  247. for (auto & elem : source)
  248. for (size_t image=0; image < elem.second.size(); image++)
  249. unloadFrame(image, elem.first);
  250. }
  251. void CAnimation::preload()
  252. {
  253. if(!preloaded)
  254. {
  255. preloaded = true;
  256. load();
  257. }
  258. }
  259. void CAnimation::loadGroup(size_t group)
  260. {
  261. if (vstd::contains(source, group))
  262. for (size_t image=0; image < source[group].size(); image++)
  263. loadFrame(image, group);
  264. }
  265. void CAnimation::unloadGroup(size_t group)
  266. {
  267. if (vstd::contains(source, group))
  268. for (size_t image=0; image < source[group].size(); image++)
  269. unloadFrame(image, group);
  270. }
  271. void CAnimation::load(size_t frame, size_t group)
  272. {
  273. loadFrame(frame, group);
  274. }
  275. void CAnimation::unload(size_t frame, size_t group)
  276. {
  277. unloadFrame(frame, group);
  278. }
  279. size_t CAnimation::size(size_t group) const
  280. {
  281. auto iter = source.find(group);
  282. if (iter != source.end())
  283. return iter->second.size();
  284. return 0;
  285. }
  286. void CAnimation::horizontalFlip()
  287. {
  288. for(auto & group : images)
  289. for(auto & image : group.second)
  290. image.second->horizontalFlip();
  291. }
  292. void CAnimation::verticalFlip()
  293. {
  294. for(auto & group : images)
  295. for(auto & image : group.second)
  296. image.second->verticalFlip();
  297. }
  298. void CAnimation::playerColored(PlayerColor player)
  299. {
  300. for(auto & group : images)
  301. for(auto & image : group.second)
  302. image.second->playerColored(player);
  303. }
  304. void CAnimation::createFlippedGroup(const size_t sourceGroup, const size_t targetGroup)
  305. {
  306. for(size_t frame = 0; frame < size(sourceGroup); ++frame)
  307. {
  308. duplicateImage(sourceGroup, frame, targetGroup);
  309. auto image = getImage(frame, targetGroup);
  310. image->verticalFlip();
  311. }
  312. }