RenderHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 "ScalableImage.h"
  14. #include "FontChain.h"
  15. #include "../gui/CGuiHandler.h"
  16. #include "../render/CAnimation.h"
  17. #include "../render/CanvasImage.h"
  18. #include "../render/CDefFile.h"
  19. #include "../render/Colors.h"
  20. #include "../render/ColorFilter.h"
  21. #include "../render/IScreenHandler.h"
  22. #include "../../lib/CConfigHandler.h"
  23. #include "../../lib/CThreadHelper.h"
  24. #include "../../lib/ExceptionsCommon.h"
  25. #include "../../lib/VCMIDirs.h"
  26. #include "../../lib/constants/StringConstants.h"
  27. #include "../../lib/entities/building/CBuilding.h"
  28. #include "../../lib/entities/faction/CTown.h"
  29. #include "../../lib/entities/faction/CTownHandler.h"
  30. #include "../../lib/filesystem/Filesystem.h"
  31. #include "../../lib/json/JsonUtils.h"
  32. #include <vcmi/ArtifactService.h>
  33. #include <vcmi/CreatureService.h>
  34. #include <vcmi/Entity.h>
  35. #include <vcmi/FactionService.h>
  36. #include <vcmi/HeroTypeService.h>
  37. #include <vcmi/Services.h>
  38. #include <vcmi/SkillService.h>
  39. #include <vcmi/spells/Service.h>
  40. std::shared_ptr<CDefFile> RenderHandler::getAnimationFile(const AnimationPath & path)
  41. {
  42. AnimationPath actualPath = boost::starts_with(path.getName(), "SPRITES") ? path : path.addPrefix("SPRITES/");
  43. auto it = animationFiles.find(actualPath);
  44. if (it != animationFiles.end())
  45. return it->second;
  46. if (!CResourceHandler::get()->existsResource(actualPath))
  47. {
  48. animationFiles[actualPath] = nullptr;
  49. return nullptr;
  50. }
  51. auto result = std::make_shared<CDefFile>(actualPath);
  52. animationFiles[actualPath] = result;
  53. return result;
  54. }
  55. void RenderHandler::initFromJson(AnimationLayoutMap & source, const JsonNode & config, EImageBlitMode mode)
  56. {
  57. std::string basepath;
  58. basepath = config["basepath"].String();
  59. JsonNode base;
  60. base["margins"] = config["margins"];
  61. base["width"] = config["width"];
  62. base["height"] = config["height"];
  63. for(const JsonNode & group : config["sequences"].Vector())
  64. {
  65. size_t groupID = group["group"].Integer();//TODO: string-to-value conversion("moving" -> MOVING)
  66. source[groupID].clear();
  67. for(const JsonNode & frame : group["frames"].Vector())
  68. {
  69. JsonNode toAdd = frame;
  70. JsonUtils::inherit(toAdd, base);
  71. toAdd["file"].String() = basepath + frame.String();
  72. source[groupID].emplace_back(toAdd, mode);
  73. }
  74. }
  75. for(const JsonNode & node : config["images"].Vector())
  76. {
  77. size_t group = node["group"].Integer();
  78. size_t frame = node["frame"].Integer();
  79. if (source[group].size() <= frame)
  80. source[group].resize(frame+1);
  81. JsonNode toAdd = node;
  82. JsonUtils::inherit(toAdd, base);
  83. if (toAdd.Struct().count("file"))
  84. toAdd["file"].String() = basepath + node["file"].String();
  85. if (toAdd.Struct().count("defFile"))
  86. toAdd["defFile"].String() = basepath + node["defFile"].String();
  87. source[group][frame] = ImageLocator(toAdd, mode);
  88. }
  89. }
  90. RenderHandler::AnimationLayoutMap & RenderHandler::getAnimationLayout(const AnimationPath & path, int scalingFactor, EImageBlitMode mode)
  91. {
  92. static constexpr std::array scaledSpritesPath = {
  93. "", // 0x
  94. "SPRITES/",
  95. "SPRITES2X/",
  96. "SPRITES3X/",
  97. "SPRITES4X/",
  98. };
  99. std::string pathString = path.getName();
  100. if (boost::starts_with(pathString, "SPRITES/"))
  101. pathString = pathString.substr(std::string("SPRITES/").length());
  102. AnimationPath actualPath = AnimationPath::builtin(scaledSpritesPath.at(scalingFactor) + pathString);
  103. auto it = animationLayouts.find(actualPath);
  104. if (it != animationLayouts.end())
  105. return it->second;
  106. AnimationLayoutMap result;
  107. auto defFile = getAnimationFile(actualPath);
  108. if(defFile)
  109. {
  110. const std::map<size_t, size_t> defEntries = defFile->getEntries();
  111. for (const auto & defEntry : defEntries)
  112. result[defEntry.first].resize(defEntry.second);
  113. }
  114. auto jsonResource = actualPath.toType<EResType::JSON>();
  115. auto configList = CResourceHandler::get()->getResourcesWithName(jsonResource);
  116. for(auto & loader : configList)
  117. {
  118. try {
  119. auto stream = loader->load(jsonResource);
  120. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  121. stream->read(textData.get(), stream->getSize());
  122. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), path.getOriginalName());
  123. initFromJson(result, config, mode);
  124. }
  125. catch (const DataLoadingException & e)
  126. {
  127. // FIXME: sometimes triggered by generated animation assets, e.g. lava/water tiles
  128. logGlobal->error("Failed to load animation file! Reason: %s", e.what());
  129. }
  130. }
  131. animationLayouts[actualPath] = result;
  132. return animationLayouts[actualPath];
  133. }
  134. int RenderHandler::getScalingFactor() const
  135. {
  136. return GH.screenHandler().getScalingFactor();
  137. }
  138. ImageLocator RenderHandler::getLocatorForAnimationFrame(const AnimationPath & path, int frame, int group, int scaling, EImageBlitMode mode)
  139. {
  140. const auto & layout = getAnimationLayout(path, scaling, mode);
  141. if (!layout.count(group))
  142. return ImageLocator();
  143. if (frame >= layout.at(group).size())
  144. return ImageLocator();
  145. const auto & locator = layout.at(group).at(frame);
  146. if (locator.image || locator.defFile)
  147. return locator;
  148. return ImageLocator(path, frame, group, mode);
  149. }
  150. std::shared_ptr<ScalableImageShared> RenderHandler::loadImageImpl(const ImageLocator & locator)
  151. {
  152. auto it = imageFiles.find(locator);
  153. if (it != imageFiles.end())
  154. return it->second;
  155. auto sdlImage = loadImageFromFileUncached(locator);
  156. auto scaledImage = std::make_shared<ScalableImageShared>(locator, sdlImage);
  157. storeCachedImage(locator, scaledImage);
  158. return scaledImage;
  159. }
  160. std::shared_ptr<SDLImageShared> RenderHandler::loadImageFromFileUncached(const ImageLocator & locator)
  161. {
  162. if(locator.image)
  163. {
  164. // TODO: create EmptySharedImage class that will be instantiated if image does not exists or fails to load
  165. return std::make_shared<SDLImageShared>(*locator.image);
  166. }
  167. if(locator.defFile)
  168. {
  169. auto defFile = getAnimationFile(*locator.defFile);
  170. if(defFile->hasFrame(locator.defFrame, locator.defGroup))
  171. return std::make_shared<SDLImageShared>(defFile.get(), locator.defFrame, locator.defGroup);
  172. else
  173. {
  174. logGlobal->error("Frame %d in group %d not found in file: %s",
  175. locator.defFrame, locator.defGroup, locator.defFile->getName().c_str());
  176. return std::make_shared<SDLImageShared>(ImagePath::builtin("DEFAULT"));
  177. }
  178. }
  179. throw std::runtime_error("Invalid image locator received!");
  180. }
  181. void RenderHandler::storeCachedImage(const ImageLocator & locator, std::shared_ptr<ScalableImageShared> image)
  182. {
  183. imageFiles[locator] = image;
  184. }
  185. std::shared_ptr<SDLImageShared> RenderHandler::loadScaledImage(const ImageLocator & locator)
  186. {
  187. static constexpr std::array scaledDataPath = {
  188. "", // 0x
  189. "DATA/",
  190. "DATA2X/",
  191. "DATA3X/",
  192. "DATA4X/",
  193. };
  194. static constexpr std::array scaledSpritesPath = {
  195. "", // 0x
  196. "SPRITES/",
  197. "SPRITES2X/",
  198. "SPRITES3X/",
  199. "SPRITES4X/",
  200. };
  201. ImagePath pathToLoad;
  202. if(locator.defFile)
  203. {
  204. auto remappedLocator = getLocatorForAnimationFrame(*locator.defFile, locator.defFrame, locator.defGroup, locator.scalingFactor, locator.layer);
  205. // we expect that .def's are only used for 1x data, upscaled assets should use standalone images
  206. if (!remappedLocator.image)
  207. return nullptr;
  208. pathToLoad = *remappedLocator.image;
  209. }
  210. if(locator.image)
  211. pathToLoad = *locator.image;
  212. if (pathToLoad.empty())
  213. return nullptr;
  214. std::string imagePathString = pathToLoad.getName();
  215. if(locator.layer == EImageBlitMode::ONLY_OVERLAY)
  216. imagePathString += "-OVERLAY";
  217. if(locator.layer == EImageBlitMode::ONLY_SHADOW)
  218. imagePathString += "-SHADOW";
  219. if(locator.playerColored.isValidPlayer())
  220. imagePathString += "-" + boost::to_upper_copy(GameConstants::PLAYER_COLOR_NAMES[locator.playerColored.getNum()]);
  221. if(locator.playerColored == PlayerColor::NEUTRAL)
  222. imagePathString += "-NEUTRAL";
  223. auto imagePath = ImagePath::builtin(imagePathString);
  224. auto imagePathSprites = ImagePath::builtin(imagePathString).addPrefix(scaledSpritesPath.at(locator.scalingFactor));
  225. auto imagePathData = ImagePath::builtin(imagePathString).addPrefix(scaledDataPath.at(locator.scalingFactor));
  226. if(CResourceHandler::get()->existsResource(imagePathSprites))
  227. return std::make_shared<SDLImageShared>(imagePathSprites);
  228. if(CResourceHandler::get()->existsResource(imagePathData))
  229. return std::make_shared<SDLImageShared>(imagePathData);
  230. if(CResourceHandler::get()->existsResource(imagePath))
  231. return std::make_shared<SDLImageShared>(imagePath);
  232. return nullptr;
  233. }
  234. std::shared_ptr<IImage> RenderHandler::loadImage(const ImageLocator & locator)
  235. {
  236. ImageLocator adjustedLocator = locator;
  237. std::shared_ptr<ScalableImageInstance> result;
  238. if (adjustedLocator.scalingFactor == 0)
  239. {
  240. auto scaledLocator = adjustedLocator;
  241. scaledLocator.scalingFactor = getScalingFactor();
  242. result = loadImageImpl(scaledLocator)->createImageReference();
  243. }
  244. else
  245. result = loadImageImpl(adjustedLocator)->createImageReference();
  246. if (locator.horizontalFlip)
  247. result->horizontalFlip();
  248. if (locator.verticalFlip)
  249. result->verticalFlip();
  250. return result;
  251. }
  252. std::shared_ptr<IImage> RenderHandler::loadImage(const AnimationPath & path, int frame, int group, EImageBlitMode mode)
  253. {
  254. ImageLocator locator = getLocatorForAnimationFrame(path, frame, group, 1, mode);
  255. if (!locator.empty())
  256. return loadImage(locator);
  257. else
  258. return loadImage(ImageLocator(ImagePath::builtin("DEFAULT"), mode));
  259. }
  260. std::shared_ptr<IImage> RenderHandler::loadImage(const ImagePath & path, EImageBlitMode mode)
  261. {
  262. ImageLocator locator(path, mode);
  263. return loadImage(locator);
  264. }
  265. std::shared_ptr<CanvasImage> RenderHandler::createImage(const Point & size, CanvasScalingPolicy scalingPolicy)
  266. {
  267. return std::make_shared<CanvasImage>(size, scalingPolicy);
  268. }
  269. std::shared_ptr<CAnimation> RenderHandler::loadAnimation(const AnimationPath & path, EImageBlitMode mode)
  270. {
  271. return std::make_shared<CAnimation>(path, getAnimationLayout(path, 1, mode), mode);
  272. }
  273. void RenderHandler::addImageListEntries(const EntityService * service)
  274. {
  275. service->forEachBase([this](const Entity * entity, bool & stop)
  276. {
  277. entity->registerIcons([this](size_t index, size_t group, const std::string & listName, const std::string & imageName)
  278. {
  279. if (imageName.empty())
  280. return;
  281. auto & layout = getAnimationLayout(AnimationPath::builtin("SPRITES/" + listName), 1, EImageBlitMode::SIMPLE);
  282. JsonNode entry;
  283. entry["file"].String() = imageName;
  284. if (index >= layout[group].size())
  285. layout[group].resize(index + 1);
  286. layout[group][index] = ImageLocator(entry, EImageBlitMode::SIMPLE);
  287. });
  288. });
  289. }
  290. static void detectOverlappingBuildings(RenderHandler * renderHandler, const Faction * factionBase)
  291. {
  292. if (!factionBase->hasTown())
  293. return;
  294. auto faction = dynamic_cast<const CFaction*>(factionBase);
  295. for (const auto & left : faction->town->clientInfo.structures)
  296. {
  297. for (const auto & right : faction->town->clientInfo.structures)
  298. {
  299. if (left->identifier <= right->identifier)
  300. continue; // only a<->b comparison is needed, not a<->a or b<->a
  301. if (left->building && right->building && left->building->getBase() == right->building->getBase())
  302. continue; // upgrades of the same buildings are expected to overlap
  303. if (left->pos.z != right->pos.z)
  304. continue; // buildings already have different z-index and have well-defined overlap logic
  305. auto leftImage = renderHandler->loadImage(left->defName, 0, 0, EImageBlitMode::SIMPLE);
  306. auto rightImage = renderHandler->loadImage(right->defName, 0, 0, EImageBlitMode::SIMPLE);
  307. Rect leftRect( left->pos.x, left->pos.y, leftImage->width(), leftImage->height());
  308. Rect rightRect( right->pos.x, right->pos.y, rightImage->width(), rightImage->height());
  309. Rect intersection = leftRect.intersect(rightRect);
  310. Point intersectionPosition;
  311. bool intersectionFound = false;
  312. for (int y = 0; y < intersection.h && !intersectionFound; ++y)
  313. {
  314. for (int x = 0; x < intersection.w && !intersectionFound; ++x)
  315. {
  316. Point leftPoint = Point(x,y) - leftRect.topLeft() + intersection.topLeft();
  317. Point rightPoint = Point(x,y) - rightRect.topLeft() + intersection.topLeft();
  318. if (!leftImage->isTransparent(leftPoint) && !rightImage->isTransparent(rightPoint))
  319. {
  320. intersectionFound = true;
  321. intersectionPosition = intersection.topLeft() + Point(x,y);
  322. }
  323. }
  324. }
  325. if (intersectionFound)
  326. logMod->warn("Town %s: Detected overlapping buildings '%s' and '%s' at (%d, %d) with same z-index!", faction->getJsonKey(), left->identifier, right->identifier, intersectionPosition.x, intersectionPosition.y);
  327. }
  328. }
  329. };
  330. void RenderHandler::onLibraryLoadingFinished(const Services * services)
  331. {
  332. addImageListEntries(services->creatures());
  333. addImageListEntries(services->heroTypes());
  334. addImageListEntries(services->artifacts());
  335. addImageListEntries(services->factions());
  336. addImageListEntries(services->spells());
  337. addImageListEntries(services->skills());
  338. if (settings["mods"]["validation"].String() == "full")
  339. {
  340. services->factions()->forEach([this](const Faction * factionBase, bool & stop)
  341. {
  342. detectOverlappingBuildings(this, factionBase);
  343. });
  344. }
  345. }
  346. std::shared_ptr<const IFont> RenderHandler::loadFont(EFonts font)
  347. {
  348. if (fonts.count(font))
  349. return fonts.at(font);
  350. const int8_t index = static_cast<int8_t>(font);
  351. logGlobal->debug("Loading font %d", static_cast<int>(index));
  352. auto configList = CResourceHandler::get()->getResourcesWithName(JsonPath::builtin("config/fonts.json"));
  353. std::shared_ptr<FontChain> loadedFont = std::make_shared<FontChain>();
  354. std::string bitmapPath;
  355. for(auto & loader : configList)
  356. {
  357. auto stream = loader->load(JsonPath::builtin("config/fonts.json"));
  358. std::unique_ptr<ui8[]> textData(new ui8[stream->getSize()]);
  359. stream->read(textData.get(), stream->getSize());
  360. const JsonNode config(reinterpret_cast<const std::byte*>(textData.get()), stream->getSize(), "config/fonts.json");
  361. const JsonVector & bmpConf = config["bitmap"].Vector();
  362. const JsonNode & ttfConf = config["trueType"];
  363. bitmapPath = bmpConf[index].String();
  364. if (!ttfConf[bitmapPath].isNull())
  365. loadedFont->addTrueTypeFont(ttfConf[bitmapPath]);
  366. }
  367. loadedFont->addBitmapFont(bitmapPath);
  368. fonts[font] = loadedFont;
  369. return loadedFont;
  370. }