RenderHandler.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * RenderHandler.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 "RenderHandler.h"
  12. #include "SDLImage.h"
  13. #include "ImageScaled.h"
  14. #include "../gui/CGuiHandler.h"
  15. #include "../render/CAnimation.h"
  16. #include "../render/CDefFile.h"
  17. #include "../render/Colors.h"
  18. #include "../render/ColorFilter.h"
  19. #include "../render/IScreenHandler.h"
  20. #include "../../lib/json/JsonUtils.h"
  21. #include "../../lib/filesystem/Filesystem.h"
  22. #include <vcmi/ArtifactService.h>
  23. #include <vcmi/CreatureService.h>
  24. #include <vcmi/Entity.h>
  25. #include <vcmi/FactionService.h>
  26. #include <vcmi/HeroTypeService.h>
  27. #include <vcmi/Services.h>
  28. #include <vcmi/SkillService.h>
  29. #include <vcmi/spells/Service.h>
  30. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  31. {
  32. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  33. auto it = animationFiles.find(actualPath);
  34. if (it != animationFiles.end())
  35. return it->second;
  36. if (!CResourceHandler::get()->existsResource(actualPath))
  37. {
  38. animationFiles[actualPath] = nullptr;
  39. return nullptr;
  40. }
  41. auto result = std::make_shared<CDefFile>(actualPath);
  42. animationFiles[actualPath] = result;
  43. return result;
  44. }
  45. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config)
  46. {
  47. std::string basepath;
  48. basepath = config["basepath"].String();
  49. JsonNode base;
  50. base["margins"] = config["margins"];
  51. base["width"] = config["width"];
  52. base["height"] = config["height"];
  53. for(const JsonNode & group : config["sequences"].Vector())
  54. {
  55. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  56. source[groupID].clear();
  57. for(const JsonNode & frame : group["frames"].Vector())
  58. {
  59. JsonNode toAdd = frame;
  60. JsonUtils::inherit(toAdd, base);
  61. toAdd["file"].String() = basepath + frame.String();
  62. source[groupID].emplace_back(toAdd);
  63. }
  64. }
  65. for(const JsonNode & node : config["images"].Vector())
  66. {
  67. size_t group = node["group"].Integer();
  68. size_t frame = node["frame"].Integer();
  69. if (source[group].size() <= frame)
  70. source[group].resize(frame+1);
  71. JsonNode toAdd = node;
  72. JsonUtils::inherit(toAdd, base);
  73. toAdd["file"].String() = basepath + node["file"].String();
  74. source[group][frame] = ImageLocator(toAdd);
  75. }
  76. }
  77. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path)
  78. {
  79. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  80. auto it = animationLayouts.find(actualPath);
  81. if (it != animationLayouts.end())
  82. return it->second;
  83. AnimationLayoutMap result;
  84. auto defFile = getAnimationFile(actualPath);
  85. if(defFile)
  86. {
  87. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  88. for (const auto & defEntry : defEntries)
  89. result[defEntry.first].resize(defEntry.second);
  90. }
  91. auto jsonResource = actualPath.toType<EResType::JSON>();
  92. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  93. for(auto & loader : configList)
  94. {
  95. auto stream = loader->load(jsonResource);
  96. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  97. stream->read(textData.get(), stream->getSize());
  98. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  99. initFromJson(result, config);
  100. }
  101. animationLayouts[actualPath] = result;
  102. return animationLayouts[actualPath];
  103. }
  104. int RenderHandler::getScalingFactor() const
  105. {
  106. return GH.screenHandler().getScalingFactor();
  107. }
  108. std::shared_ptr<IImage> RenderHandler::createImageReference(const ImageLocator & locator, std::shared_ptr<ISharedImage> input, EImageBlitMode mode)
  109. {
  110. if (getScalingFactor() == 1 || locator.scalingFactor != 1 || locator.empty())
  111. return input->createImageReference(mode);
  112. else
  113. return std::make_shared<ImageScaled>(locator, input, mode);
  114. }
  115. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group)
  116. {
  117. const auto & layout = getAnimationLayout(path);
  118. if (!layout.count(group))
  119. return ImageLocator(ImagePath::builtin("DEFAULT"));
  120. if (frame >= layout.at(group).size())
  121. return ImageLocator(ImagePath::builtin("DEFAULT"));
  122. const auto & locator = layout.at(group).at(frame);
  123. if (locator.image || locator.defFile)
  124. return locator;
  125. return ImageLocator(path, frame, group);
  126. }
  127. std::shared_ptr<ISharedImage> RenderHandler::loadImageImpl(const ImageLocator & locator)
  128. {
  129. auto it = imageFiles.find(locator);
  130. if (it != imageFiles.end())
  131. return it->second;
  132. // TODO: order should be different:
  133. // 1) try to find correctly scaled image
  134. // 2) if fails -> try to find correctly transformed
  135. // 3) if also fails -> try to find image from correct file
  136. // 4) load missing part of the sequence
  137. // TODO: check whether (load -> transform -> scale) or (load -> scale -> transform) order should be used for proper loading of pre-scaled data
  138. auto imageFromFile = loadImageFromFile(locator.copyFile());
  139. auto transformedImage = transformImage(locator.copyFileTransform(), imageFromFile);
  140. auto scaledImage = scaleImage(locator.copyFileTransformScale(), transformedImage);
  141. return scaledImage;
  142. }
  143. std::shared_ptr<ISharedImage> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  144. {
  145. if (locator.image)
  146. {
  147. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  148. return std::make_shared<SDLImageShared>(*locator.image);
  149. }
  150. if (locator.defFile)
  151. {
  152. auto defFile = getAnimationFile(*locator.defFile);
  153. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  154. }
  155. throw std::runtime_error("Invalid image locator received!");
  156. }
  157. std::shared_ptr<ISharedImage> RenderHandler::loadImageFromFile(const ImageLocator & locator)
  158. {
  159. if (imageFiles.count(locator))
  160. return imageFiles.at(locator);
  161. auto result = loadImageFromFileUncached(locator);
  162. imageFiles[locator] = result;
  163. return result;
  164. }
  165. std::shared_ptr<ISharedImage> RenderHandler::transformImage(const ImageLocator & locator, std::shared_ptr<ISharedImage> image)
  166. {
  167. if (imageFiles.count(locator))
  168. return imageFiles.at(locator);
  169. auto result = image;
  170. if (locator.verticalFlip)
  171. result = result->verticalFlip();
  172. if (locator.horizontalFlip)
  173. result = result->horizontalFlip();
  174. imageFiles[locator] = result;
  175. return result;
  176. }
  177. std::shared_ptr<ISharedImage> RenderHandler::scaleImage(const ImageLocator & locator, std::shared_ptr<ISharedImage> image)
  178. {
  179. if (imageFiles.count(locator))
  180. return imageFiles.at(locator);
  181. auto handle = image->createImageReference(locator.layer == EImageLayer::ALL ? EImageBlitMode::OPAQUE : EImageBlitMode::ALPHA);
  182. assert(locator.scalingFactor != 1); // should be filtered-out before
  183. handle->setOverlayEnabled(locator.layer == EImageLayer::ALL || locator.layer == EImageLayer::OVERLAY);
  184. handle->setBodyEnabled(locator.layer == EImageLayer::ALL || locator.layer == EImageLayer::BODY);
  185. handle->setShadowEnabled(locator.layer == EImageLayer::ALL || locator.layer == EImageLayer::SHADOW);
  186. if (locator.layer == EImageLayer::ALL && locator.playerColored != PlayerColor::CANNOT_DETERMINE)
  187. handle->playerColored(locator.playerColored);
  188. handle->scaleInteger(locator.scalingFactor);
  189. // TODO: try to optimize image size (possibly even before scaling?) - trim image borders if they are completely transparent
  190. auto result = handle->getSharedImage();
  191. imageFiles[locator] = result;
  192. return result;
  193. }
  194. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator, EImageBlitMode mode)
  195. {
  196. return createImageReference(locator, loadImageImpl(locator), mode);
  197. }
  198. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  199. {
  200. auto locator = getLocatorForAnimationFrame(path, frame, group);
  201. return loadImage(locator, mode);
  202. }
  203. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  204. {
  205. return loadImage(ImageLocator(path), mode);
  206. }
  207. std::shared_ptr<IImage> RenderHandler::createImage(SDL_Surface * source)
  208. {
  209. return createImageReference(ImageLocator(), std::make_shared<SDLImageShared>(source), EImageBlitMode::ALPHA);
  210. }
  211. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  212. {
  213. return std::make_shared<CAnimation>(path, getAnimationLayout(path), mode);
  214. }
  215. void RenderHandler::addImageListEntries(const EntityService * service)
  216. {
  217. service->forEachBase([this](const Entity * entity, bool & stop)
  218. {
  219. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  220. {
  221. if (imageName.empty())
  222. return;
  223. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName));
  224. JsonNode entry;
  225. entry["file"].String() = imageName;
  226. if (index >= layout[group].size())
  227. layout[group].resize(index + 1);
  228. layout[group][index] = ImageLocator(entry);
  229. });
  230. });
  231. }
  232. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  233. {
  234. addImageListEntries(services->creatures());
  235. addImageListEntries(services->heroTypes());
  236. addImageListEntries(services->artifacts());
  237. addImageListEntries(services->factions());
  238. addImageListEntries(services->spells());
  239. addImageListEntries(services->skills());
  240. }