CAnimation.cpp 8.6 KB

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