mapHandler.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486
  1. /*
  2. * mapHandler.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 "mapHandler.h"
  12. #include "../render/CAnimation.h"
  13. #include "../render/CFadeAnimation.h"
  14. #include "../render/Colors.h"
  15. #include "../renderSDL/SDL_Extensions.h"
  16. #include "../CGameInfo.h"
  17. #include "../render/Graphics.h"
  18. #include "../render/IImage.h"
  19. #include "../CMusicHandler.h"
  20. #include "../../lib/mapObjects/CGHeroInstance.h"
  21. #include "../../lib/mapObjects/CObjectClassesHandler.h"
  22. #include "../../lib/mapping/CMap.h"
  23. #include "../../lib/Color.h"
  24. #include "../../lib/CConfigHandler.h"
  25. #include "../../lib/CGeneralTextHandler.h"
  26. #include "../../lib/CStopWatch.h"
  27. #include "../../lib/CRandomGenerator.h"
  28. #include "../../lib/RoadHandler.h"
  29. #include "../../lib/RiverHandler.h"
  30. #include "../../lib/TerrainHandler.h"
  31. #define ADVOPT (conf.go()->ac)
  32. static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
  33. {
  34. return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
  35. }
  36. struct NeighborTilesInfo
  37. {
  38. bool d7, //789
  39. d8, //456
  40. d9, //123
  41. d4,
  42. d5,
  43. d6,
  44. d1,
  45. d2,
  46. d3;
  47. NeighborTilesInfo(const int3 & pos, const int3 & sizes, std::shared_ptr<const boost::multi_array<ui8, 3>> visibilityMap)
  48. {
  49. auto getTile = [&](int dx, int dy)->bool
  50. {
  51. if ( dx + pos.x < 0 || dx + pos.x >= sizes.x
  52. || dy + pos.y < 0 || dy + pos.y >= sizes.y)
  53. return false;
  54. //FIXME: please do not read settings for every tile...
  55. return settings["session"]["spectate"].Bool() ? true : (*visibilityMap)[pos.z][dx+pos.x][dy+pos.y];
  56. };
  57. d7 = getTile(-1, -1); //789
  58. d8 = getTile( 0, -1); //456
  59. d9 = getTile(+1, -1); //123
  60. d4 = getTile(-1, 0);
  61. d5 = (*visibilityMap)[pos.z][pos.x][pos.y];
  62. d6 = getTile(+1, 0);
  63. d1 = getTile(-1, +1);
  64. d2 = getTile( 0, +1);
  65. d3 = getTile(+1, +1);
  66. }
  67. bool areAllHidden() const
  68. {
  69. return !(d1 || d2 || d3 || d4 || d5 || d6 || d7 || d8 || d9);
  70. }
  71. int getBitmapID() const
  72. {
  73. //NOTE: some images have unused in VCMI pair (same blockmap but a bit different look)
  74. // 0-1, 2-3, 4-5, 11-13, 12-14
  75. static const int visBitmaps[256] = {
  76. -1, 34, 4, 4, 22, 23, 4, 4, 36, 36, 38, 38, 47, 47, 38, 38, //16
  77. 3, 25, 12, 12, 3, 25, 12, 12, 9, 9, 6, 6, 9, 9, 6, 6, //32
  78. 35, 39, 48, 48, 41, 43, 48, 48, 36, 36, 38, 38, 47, 47, 38, 38, //48
  79. 26, 49, 28, 28, 26, 49, 28, 28, 9, 9, 6, 6, 9, 9, 6, 6, //64
  80. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //80
  81. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //96
  82. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //112
  83. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //128
  84. 15, 17, 30, 30, 16, 19, 30, 30, 46, 46, 40, 40, 32, 32, 40, 40, //144
  85. 2, 25, 12, 12, 2, 25, 12, 12, 9, 9, 6, 6, 9, 9, 6, 6, //160
  86. 18, 42, 31, 31, 20, 21, 31, 31, 46, 46, 40, 40, 32, 32, 40, 40, //176
  87. 26, 49, 28, 28, 26, 49, 28, 28, 9, 9, 6, 6, 9, 9, 6, 6, //192
  88. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //208
  89. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10, //224
  90. 0, 45, 29, 29, 24, 33, 29, 29, 37, 37, 7, 7, 50, 50, 7, 7, //240
  91. 13, 27, 44, 44, 13, 27, 44, 44, 8, 8, 10, 10, 8, 8, 10, 10 //256
  92. };
  93. return visBitmaps[d1 + d2 * 2 + d3 * 4 + d4 * 8 + d6 * 16 + d7 * 32 + d8 * 64 + d9 * 128]; // >=0 -> partial hide, <0 - full hide
  94. }
  95. };
  96. void CMapHandler::prepareFOWDefs()
  97. {
  98. //assume all frames in group 0
  99. size_t size = graphics->fogOfWarFullHide->size(0);
  100. FoWfullHide.resize(size);
  101. for(size_t frame = 0; frame < size; frame++)
  102. FoWfullHide[frame] = graphics->fogOfWarFullHide->getImage(frame);
  103. //initialization of type of full-hide image
  104. hideBitmap.resize(boost::extents[sizes.z][sizes.x][sizes.y]);
  105. for (int i = 0; i < hideBitmap.num_elements(); i++)
  106. hideBitmap.data()[i] = CRandomGenerator::getDefault().nextInt(size - 1);
  107. size = graphics->fogOfWarPartialHide->size(0);
  108. FoWpartialHide.resize(size);
  109. for(size_t frame = 0; frame < size; frame++)
  110. FoWpartialHide[frame] = graphics->fogOfWarPartialHide->getImage(frame);
  111. }
  112. EMapAnimRedrawStatus CMapHandler::drawTerrainRectNew(SDL_Surface * targetSurface, const MapDrawingInfo * info, bool redrawOnlyAnim)
  113. {
  114. assert(info);
  115. bool hasActiveFade = updateObjectsFade();
  116. resolveBlitter(info)->blit(targetSurface, info);
  117. return hasActiveFade ? EMapAnimRedrawStatus::REDRAW_REQUESTED : EMapAnimRedrawStatus::OK;
  118. }
  119. void CMapHandler::initTerrainGraphics()
  120. {
  121. auto loadFlipped = [](TFlippedAnimations & animation, TFlippedCache & cache, const std::map<std::string, std::string> & files)
  122. {
  123. //no rotation and basic setup
  124. for(auto & type : files)
  125. {
  126. animation[type.first][0] = std::make_unique<CAnimation>(type.second);
  127. animation[type.first][0]->preload();
  128. const size_t views = animation[type.first][0]->size(0);
  129. cache[type.first].resize(views);
  130. for(int j = 0; j < views; j++)
  131. cache[type.first][j][0] = animation[type.first][0]->getImage(j);
  132. }
  133. for(int rotation = 1; rotation < 4; rotation++)
  134. {
  135. for(auto & type : files)
  136. {
  137. animation[type.first][rotation] = std::make_unique<CAnimation>(type.second);
  138. animation[type.first][rotation]->preload();
  139. const size_t views = animation[type.first][rotation]->size(0);
  140. for(int j = 0; j < views; j++)
  141. {
  142. auto image = animation[type.first][rotation]->getImage(j);
  143. if(rotation == 2 || rotation == 3)
  144. image->horizontalFlip();
  145. if(rotation == 1 || rotation == 3)
  146. image->verticalFlip();
  147. cache[type.first][j][rotation] = image;
  148. }
  149. }
  150. }
  151. };
  152. std::map<std::string, std::string> terrainFiles;
  153. std::map<std::string, std::string> riverFiles;
  154. std::map<std::string, std::string> roadFiles;
  155. for(const auto & terrain : VLC->terrainTypeHandler->objects)
  156. {
  157. terrainFiles[terrain->getJsonKey()] = terrain->tilesFilename;
  158. }
  159. for(const auto & river : VLC->riverTypeHandler->objects)
  160. {
  161. riverFiles[river->getJsonKey()] = river->tilesFilename;
  162. }
  163. for(const auto & road : VLC->roadTypeHandler->objects)
  164. {
  165. roadFiles[road->getJsonKey()] = road->tilesFilename;
  166. }
  167. loadFlipped(terrainAnimations, terrainImages, terrainFiles);
  168. loadFlipped(riverAnimations, riverImages, riverFiles);
  169. loadFlipped(roadAnimations, roadImages, roadFiles);
  170. // Create enough room for the whole map and its frame
  171. //ttiles.resize(sizes.x, frameW, frameW);
  172. //FIXME: why do we even handle array with z (surface and undeground) at the same time?
  173. ttiles.resize(boost::extents[sizes.z][sizes.x + 2 * frameW][sizes.y + 2 * frameH]);
  174. ttiles.reindex(std::list<int>{ 0, -frameW, -frameH }); //need to move starting coordinates so that used index is always positive
  175. }
  176. void CMapHandler::initBorderGraphics()
  177. {
  178. egdeImages.resize(egdeAnimation->size(0));
  179. for(size_t i = 0; i < egdeImages.size(); i++)
  180. egdeImages[i] = egdeAnimation->getImage(i);
  181. edgeFrames.resize(sizes.x, frameW, frameW);
  182. for (int i=0-frameW;i<edgeFrames.size()-frameW;i++)
  183. {
  184. edgeFrames[i].resize(sizes.y, frameH, frameH);
  185. }
  186. for (int i=0-frameW;i<edgeFrames.size()-frameW;i++)
  187. {
  188. for (int j=0-frameH;j<(int)sizes.y+frameH;j++)
  189. edgeFrames[i][j].resize(sizes.z, 0, 0);
  190. }
  191. auto & rand = CRandomGenerator::getDefault();
  192. for (int i=0-frameW; i<sizes.x+frameW; i++) //by width
  193. {
  194. for (int j=0-frameH; j<sizes.y+frameH;j++) //by height
  195. {
  196. for(int k=0; k<sizes.z; ++k) //by levels
  197. {
  198. ui8 terBitmapNum = 0;
  199. if(i < 0 || i > (sizes.x-1) || j < 0 || j > (sizes.y-1))
  200. {
  201. if(i==-1 && j==-1)
  202. terBitmapNum = 16;
  203. else if(i==-1 && j==(sizes.y))
  204. terBitmapNum = 19;
  205. else if(i==(sizes.x) && j==-1)
  206. terBitmapNum = 17;
  207. else if(i==(sizes.x) && j==(sizes.y))
  208. terBitmapNum = 18;
  209. else if(j == -1 && i > -1 && i < sizes.x)
  210. terBitmapNum = rand.nextInt(22, 23);
  211. else if(i == -1 && j > -1 && j < sizes.y)
  212. terBitmapNum = rand.nextInt(33, 34);
  213. else if(j == sizes.y && i >-1 && i < sizes.x)
  214. terBitmapNum = rand.nextInt(29, 30);
  215. else if(i == sizes.x && j > -1 && j < sizes.y)
  216. terBitmapNum = rand.nextInt(25, 26);
  217. else
  218. terBitmapNum = rand.nextInt(15);
  219. }
  220. edgeFrames[i][j][k] = terBitmapNum;
  221. }
  222. }
  223. }
  224. }
  225. void CMapHandler::initObjectRects()
  226. {
  227. //initializing objects / rects
  228. for(auto & elem : map->objects)
  229. {
  230. const CGObjectInstance *obj = elem;
  231. if( !obj
  232. || (obj->ID==Obj::HERO && static_cast<const CGHeroInstance*>(obj)->inTownGarrison) //garrisoned hero
  233. || (obj->ID==Obj::BOAT && static_cast<const CGBoat*>(obj)->hero)) //boat with hero (hero graphics is used)
  234. {
  235. continue;
  236. }
  237. std::shared_ptr<CAnimation> animation = graphics->getAnimation(obj);
  238. //no animation at all
  239. if(!animation)
  240. continue;
  241. //empty animation
  242. if(animation->size(0) == 0)
  243. continue;
  244. auto image = animation->getImage(0,0);
  245. for(int fx=0; fx < obj->getWidth(); ++fx)
  246. {
  247. for(int fy=0; fy < obj->getHeight(); ++fy)
  248. {
  249. int3 currTile(obj->pos.x - fx, obj->pos.y - fy, obj->pos.z);
  250. Rect cr;
  251. cr.w = 32;
  252. cr.h = 32;
  253. cr.x = image->width() - fx * 32 - 32;
  254. cr.y = image->height() - fy * 32 - 32;
  255. TerrainTileObject toAdd(obj, cr, obj->visitableAt(currTile.x, currTile.y));
  256. if( map->isInTheMap(currTile) && // within map
  257. cr.x + cr.w > 0 && // image has data on this tile
  258. cr.y + cr.h > 0 &&
  259. obj->coveringAt(currTile.x, currTile.y) // object is visible here
  260. )
  261. {
  262. ttiles[currTile.z][currTile.x][currTile.y].objects.push_back(toAdd);
  263. }
  264. }
  265. }
  266. }
  267. auto shape = ttiles.shape();
  268. for(size_t z = 0; z < shape[0]; z++)
  269. {
  270. for(size_t x = 0; x < shape[1] - frameW; x++)
  271. {
  272. for(size_t y = 0; y < shape[2] - frameH; y++)
  273. {
  274. auto & objects = ttiles[z][x][y].objects;
  275. stable_sort(objects.begin(), objects.end(), objectBlitOrderSorter);
  276. }
  277. }
  278. }
  279. }
  280. void CMapHandler::init()
  281. {
  282. CStopWatch th;
  283. th.getDiff();
  284. // Size of visible terrain.
  285. int mapW = conf.go()->ac.advmapW;
  286. int mapH = conf.go()->ac.advmapH;
  287. //sizes of terrain
  288. sizes.x = map->width;
  289. sizes.y = map->height;
  290. sizes.z = map->levels();
  291. // Total number of visible tiles. Subtract the center tile, then
  292. // compute the number of tiles on each side, and reassemble.
  293. int t1, t2;
  294. t1 = (mapW-32)/2;
  295. t2 = mapW - 32 - t1;
  296. tilesW = 1 + (t1+31)/32 + (t2+31)/32;
  297. t1 = (mapH-32)/2;
  298. t2 = mapH - 32 - t1;
  299. tilesH = 1 + (t1+31)/32 + (t2+31)/32;
  300. // Size of the frame around the map. In extremes positions, the
  301. // frame must not be on the center of the map, but right on the
  302. // edge of the center tile.
  303. frameW = (mapW+31) /32 / 2;
  304. frameH = (mapH+31) /32 / 2;
  305. offsetX = (mapW - (2*frameW+1)*32)/2;
  306. offsetY = (mapH - (2*frameH+1)*32)/2;
  307. prepareFOWDefs();
  308. initTerrainGraphics();
  309. initBorderGraphics();
  310. logGlobal->info("\tPreparing FoW, terrain, roads, rivers, borders: %d ms", th.getDiff());
  311. initObjectRects();
  312. logGlobal->info("\tMaking object rects: %d ms", th.getDiff());
  313. }
  314. CMapHandler::CMapBlitter *CMapHandler::resolveBlitter(const MapDrawingInfo * info) const
  315. {
  316. if (info->scaled)
  317. return worldViewBlitter;
  318. if (info->puzzleMode)
  319. return puzzleViewBlitter;
  320. return normalBlitter;
  321. }
  322. void CMapHandler::CMapNormalBlitter::drawElement(EMapCacheType cacheType, std::shared_ptr<IImage> source, Rect * sourceRect, SDL_Surface * targetSurf, Rect * destRect) const
  323. {
  324. source->draw(targetSurf, destRect, sourceRect);
  325. }
  326. void CMapHandler::CMapNormalBlitter::init(const MapDrawingInfo * drawingInfo)
  327. {
  328. info = drawingInfo;
  329. // Width and height of the portion of the map to process. Units in tiles.
  330. tileCount.x = parent->tilesW;
  331. tileCount.y = parent->tilesH;
  332. topTile = info->topTile;
  333. initPos.x = parent->offsetX + info->drawBounds.x;
  334. initPos.y = parent->offsetY + info->drawBounds.y;
  335. realTileRect = Rect(initPos.x, initPos.y, tileSize, tileSize);
  336. // If moving, we need to add an extra column/line
  337. if (info->movement.x != 0)
  338. {
  339. tileCount.x++;
  340. initPos.x += info->movement.x;
  341. if (info->movement.x > 0)
  342. {
  343. // Moving right. We still need to draw the old tile on the
  344. // left, so adjust our referential
  345. topTile.x--;
  346. initPos.x -= tileSize;
  347. }
  348. }
  349. if (info->movement.y != 0)
  350. {
  351. tileCount.y++;
  352. initPos.y += info->movement.y;
  353. if (info->movement.y > 0)
  354. {
  355. // Moving down. We still need to draw the tile on the top,
  356. // so adjust our referential.
  357. topTile.y--;
  358. initPos.y -= tileSize;
  359. }
  360. }
  361. // Reduce sizes if we go out of the full map.
  362. if (topTile.x < -parent->frameW)
  363. topTile.x = -parent->frameW;
  364. if (topTile.y < -parent->frameH)
  365. topTile.y = -parent->frameH;
  366. if (topTile.x + tileCount.x > parent->sizes.x + parent->frameW)
  367. tileCount.x = parent->sizes.x + parent->frameW - topTile.x;
  368. if (topTile.y + tileCount.y > parent->sizes.y + parent->frameH)
  369. tileCount.y = parent->sizes.y + parent->frameH - topTile.y;
  370. }
  371. Rect CMapHandler::CMapNormalBlitter::clip(SDL_Surface * targetSurf) const
  372. {
  373. Rect prevClip;
  374. CSDL_Ext::getClipRect(targetSurf, prevClip);
  375. CSDL_Ext::setClipRect(targetSurf, info->drawBounds);
  376. return prevClip;
  377. }
  378. CMapHandler::CMapNormalBlitter::CMapNormalBlitter(CMapHandler * parent)
  379. : CMapBlitter(parent)
  380. {
  381. tileSize = 32;
  382. halfTileSizeCeil = 16;
  383. defaultTileRect = Rect(0, 0, tileSize, tileSize);
  384. }
  385. std::shared_ptr<IImage> CMapHandler::CMapWorldViewBlitter::objectToIcon(Obj id, si32 subId, PlayerColor owner) const
  386. {
  387. int ownerIndex = 0;
  388. if(owner < PlayerColor::PLAYER_LIMIT)
  389. {
  390. ownerIndex = owner.getNum() * 19;
  391. }
  392. else if (owner == PlayerColor::NEUTRAL)
  393. {
  394. ownerIndex = PlayerColor::PLAYER_LIMIT.getNum() * 19;
  395. }
  396. switch(id)
  397. {
  398. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  399. case Obj::MONOLITH_ONE_WAY_EXIT:
  400. case Obj::MONOLITH_TWO_WAY:
  401. return info->icons->getImage((int)EWorldViewIcon::TELEPORT);
  402. case Obj::SUBTERRANEAN_GATE:
  403. return info->icons->getImage((int)EWorldViewIcon::GATE);
  404. case Obj::ARTIFACT:
  405. return info->icons->getImage((int)EWorldViewIcon::ARTIFACT);
  406. case Obj::TOWN:
  407. return info->icons->getImage((int)EWorldViewIcon::TOWN + ownerIndex);
  408. case Obj::HERO:
  409. return info->icons->getImage((int)EWorldViewIcon::HERO + ownerIndex);
  410. case Obj::MINE:
  411. return info->icons->getImage((int)EWorldViewIcon::MINE_WOOD + subId + ownerIndex);
  412. case Obj::RESOURCE:
  413. return info->icons->getImage((int)EWorldViewIcon::RES_WOOD + subId + ownerIndex);
  414. }
  415. return std::shared_ptr<IImage>();
  416. }
  417. void CMapHandler::CMapWorldViewBlitter::calculateWorldViewCameraPos()
  418. {
  419. bool outsideLeft = topTile.x < 0;
  420. bool outsideTop = topTile.y < 0;
  421. bool outsideRight = std::max(0, topTile.x) + tileCount.x > parent->sizes.x;
  422. bool outsideBottom = std::max(0, topTile.y) + tileCount.y > parent->sizes.y;
  423. if (tileCount.x > parent->sizes.x)
  424. topTile.x = parent->sizes.x / 2 - tileCount.x / 2; // center viewport if the whole map can fit into the screen at once
  425. else if (outsideLeft)
  426. {
  427. if (outsideRight)
  428. topTile.x = parent->sizes.x / 2 - tileCount.x / 2;
  429. else
  430. topTile.x = 0;
  431. }
  432. else if (outsideRight)
  433. topTile.x = parent->sizes.x - tileCount.x;
  434. if (tileCount.y > parent->sizes.y)
  435. topTile.y = parent->sizes.y / 2 - tileCount.y / 2;
  436. else if (outsideTop)
  437. {
  438. if (outsideBottom)
  439. topTile.y = parent->sizes.y / 2 - tileCount.y / 2;
  440. else
  441. topTile.y = 0;
  442. }
  443. else if (outsideBottom)
  444. topTile.y = parent->sizes.y - tileCount.y;
  445. }
  446. void CMapHandler::CMapWorldViewBlitter::drawElement(EMapCacheType cacheType, std::shared_ptr<IImage> source, Rect * sourceRect, SDL_Surface * targetSurf, Rect * destRect) const
  447. {
  448. auto scaled = parent->cache.requestWorldViewCacheOrCreate(cacheType, source);
  449. if(scaled)
  450. scaled->draw(targetSurf, destRect, sourceRect);
  451. }
  452. void CMapHandler::CMapWorldViewBlitter::drawTileOverlay(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  453. {
  454. auto drawIcon = [this,targetSurf](Obj id, si32 subId, PlayerColor owner)
  455. {
  456. auto wvIcon = this->objectToIcon(id, subId, owner);
  457. if(nullptr != wvIcon)
  458. {
  459. // centering icon on the object
  460. Point dest(realPos.x + tileSize / 2 - wvIcon->width() / 2, realPos.y + tileSize / 2 - wvIcon->height() / 2);
  461. wvIcon->draw(targetSurf, dest.x, dest.y);
  462. }
  463. };
  464. auto & objects = tile.objects;
  465. for(auto & object : objects)
  466. {
  467. const CGObjectInstance * obj = object.obj;
  468. if(!obj)
  469. continue;
  470. const bool sameLevel = obj->pos.z == pos.z;
  471. //FIXME: Don't read options in a loop :v
  472. const bool isVisible = settings["session"]["spectate"].Bool() ? true : (*info->visibilityMap)[pos.z][pos.x][pos.y];
  473. const bool isVisitable = obj->visitableAt(pos.x, pos.y);
  474. if(sameLevel && isVisible && isVisitable)
  475. drawIcon(obj->ID, obj->subID, obj->tempOwner);
  476. }
  477. }
  478. void CMapHandler::CMapWorldViewBlitter::drawOverlayEx(SDL_Surface * targetSurf)
  479. {
  480. if(nullptr == info->additionalIcons)
  481. return;
  482. const int3 bottomRight = pos + tileCount;
  483. for(const ObjectPosInfo & iconInfo : *(info->additionalIcons))
  484. {
  485. if( iconInfo.pos.z != pos.z)
  486. continue;
  487. if((iconInfo.pos.x < topTile.x) || (iconInfo.pos.y < topTile.y))
  488. continue;
  489. if((iconInfo.pos.x > bottomRight.x) || (iconInfo.pos.y > bottomRight.y))
  490. continue;
  491. realPos.x = initPos.x + (iconInfo.pos.x - topTile.x) * tileSize;
  492. realPos.y = initPos.y + (iconInfo.pos.y - topTile.y) * tileSize;
  493. auto wvIcon = this->objectToIcon(iconInfo.id, iconInfo.subId, iconInfo.owner);
  494. if(nullptr != wvIcon)
  495. {
  496. // centering icon on the object
  497. Point dest(realPos.x + tileSize / 2 - wvIcon->width() / 2, realPos.y + tileSize / 2 - wvIcon->height() / 2);
  498. wvIcon->draw(targetSurf, dest.x, dest.y);
  499. }
  500. }
  501. }
  502. void CMapHandler::CMapWorldViewBlitter::drawHeroFlag(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, Rect * destRect, bool moving) const
  503. {
  504. if (moving)
  505. return;
  506. CMapBlitter::drawHeroFlag(targetSurf, source, sourceRect, destRect, false);
  507. }
  508. void CMapHandler::CMapWorldViewBlitter::drawObject(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, bool moving) const
  509. {
  510. if (moving)
  511. return;
  512. Rect scaledSourceRect((int)(sourceRect->x * info->scale), (int)(sourceRect->y * info->scale), sourceRect->w, sourceRect->h);
  513. CMapBlitter::drawObject(targetSurf, source, &scaledSourceRect, false);
  514. }
  515. void CMapHandler::CMapBlitter::drawTileTerrain(SDL_Surface * targetSurf, const TerrainTile & tinfo, const TerrainTile2 & tile) const
  516. {
  517. Rect destRect(realTileRect);
  518. ui8 rotation = tinfo.extTileFlags % 4;
  519. //TODO: use ui8 instead of string key
  520. auto terrainName = tinfo.terType->getJsonKey();
  521. if(parent->terrainImages[terrainName].size()<=tinfo.terView)
  522. return;
  523. drawElement(EMapCacheType::TERRAIN, parent->terrainImages[terrainName][tinfo.terView][rotation], nullptr, targetSurf, &destRect);
  524. }
  525. void CMapHandler::CMapWorldViewBlitter::init(const MapDrawingInfo * drawingInfo)
  526. {
  527. info = drawingInfo;
  528. parent->cache.updateWorldViewScale(info->scale);
  529. topTile = info->topTile;
  530. tileSize = (int) floorf(32.0f * info->scale);
  531. halfTileSizeCeil = (int)ceilf(tileSize / 2.0f);
  532. tileCount.x = (int) ceilf((float)info->drawBounds.w / tileSize);
  533. tileCount.y = (int) ceilf((float)info->drawBounds.h / tileSize);
  534. initPos.x = info->drawBounds.x;
  535. initPos.y = info->drawBounds.y;
  536. realTileRect = Rect(initPos.x, initPos.y, tileSize, tileSize);
  537. defaultTileRect = Rect(0, 0, tileSize, tileSize);
  538. calculateWorldViewCameraPos();
  539. }
  540. Rect CMapHandler::CMapWorldViewBlitter::clip(SDL_Surface * targetSurf) const
  541. {
  542. Rect prevClip;
  543. CSDL_Ext::fillRect(targetSurf, info->drawBounds, Colors::BLACK);
  544. // makes the clip area smaller if the map is smaller than the screen frame
  545. // (actually, it could be made 1 tile bigger so that overlay icons on edge tiles could be drawn partly outside)
  546. Rect clipRect(std::max<int>(info->drawBounds.x, info->drawBounds.x - topTile.x * tileSize),
  547. std::max<int>(info->drawBounds.y, info->drawBounds.y - topTile.y * tileSize),
  548. std::min<int>(info->drawBounds.w, parent->sizes.x * tileSize),
  549. std::min<int>(info->drawBounds.h, parent->sizes.y * tileSize));
  550. CSDL_Ext::getClipRect(targetSurf, prevClip);
  551. CSDL_Ext::setClipRect(targetSurf, clipRect); //preventing blitting outside of that rect
  552. return prevClip;
  553. }
  554. CMapHandler::CMapWorldViewBlitter::CMapWorldViewBlitter(CMapHandler * parent)
  555. : CMapBlitter(parent)
  556. {
  557. }
  558. void CMapHandler::CMapPuzzleViewBlitter::drawObjects(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  559. {
  560. CMapBlitter::drawObjects(targetSurf, tile);
  561. // grail X mark
  562. if(pos.x == info->grailPos.x && pos.y == info->grailPos.y)
  563. {
  564. const auto mark = graphics->heroMoveArrows->getImage(0);
  565. mark->draw(targetSurf,realTileRect.x,realTileRect.y);
  566. }
  567. }
  568. void CMapHandler::CMapPuzzleViewBlitter::postProcessing(SDL_Surface * targetSurf) const
  569. {
  570. CSDL_Ext::applyEffect(targetSurf, info->drawBounds, static_cast<int>(!ADVOPT.puzzleSepia));
  571. }
  572. bool CMapHandler::CMapPuzzleViewBlitter::canDrawObject(const CGObjectInstance * obj) const
  573. {
  574. if (!CMapBlitter::canDrawObject(obj))
  575. return false;
  576. //don't print flaggable objects in puzzle mode
  577. if (obj->isVisitable())
  578. return false;
  579. if(std::find(unblittableObjects.begin(), unblittableObjects.end(), obj->ID) != unblittableObjects.end())
  580. return false;
  581. return true;
  582. }
  583. CMapHandler::CMapPuzzleViewBlitter::CMapPuzzleViewBlitter(CMapHandler * parent)
  584. : CMapNormalBlitter(parent)
  585. {
  586. unblittableObjects.push_back(Obj::HOLE);
  587. }
  588. CMapHandler::CMapBlitter::CMapBlitter(CMapHandler * p)
  589. :parent(p), tileSize(0), halfTileSizeCeil(0), info(nullptr)
  590. {
  591. }
  592. CMapHandler::CMapBlitter::~CMapBlitter() = default;
  593. void CMapHandler::CMapBlitter::drawFrame(SDL_Surface * targetSurf) const
  594. {
  595. Rect destRect(realTileRect);
  596. drawElement(EMapCacheType::FRAME, parent->egdeImages[parent->edgeFrames[pos.x][pos.y][topTile.z]], nullptr, targetSurf, &destRect);
  597. }
  598. void CMapHandler::CMapBlitter::drawOverlayEx(SDL_Surface * targetSurf)
  599. {
  600. //nothing to do here
  601. }
  602. void CMapHandler::CMapBlitter::drawHeroFlag(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, Rect * destRect, bool moving) const
  603. {
  604. drawElement(EMapCacheType::HERO_FLAGS, source, sourceRect, targetSurf, destRect);
  605. }
  606. void CMapHandler::CMapBlitter::drawObject(SDL_Surface * targetSurf, std::shared_ptr<IImage> source, Rect * sourceRect, bool moving) const
  607. {
  608. Rect dstRect(realTileRect);
  609. drawElement(EMapCacheType::OBJECTS, source, sourceRect, targetSurf, &dstRect);
  610. }
  611. void CMapHandler::CMapBlitter::drawObjects(SDL_Surface * targetSurf, const TerrainTile2 & tile) const
  612. {
  613. auto & objects = tile.objects;
  614. for(auto & object : objects)
  615. {
  616. if (object.fadeAnimKey >= 0)
  617. {
  618. auto fadeIter = parent->fadeAnims.find(object.fadeAnimKey);
  619. if (fadeIter != parent->fadeAnims.end())
  620. {
  621. // this object is currently fading, so skip normal drawing
  622. Rect r2(realTileRect);
  623. CFadeAnimation * fade = (*fadeIter).second.second;
  624. fade->draw(targetSurf, r2.topLeft());
  625. continue;
  626. }
  627. logGlobal->error("Fading map object with missing fade anim : %d", object.fadeAnimKey);
  628. continue;
  629. }
  630. const CGObjectInstance * obj = object.obj;
  631. if (!obj)
  632. {
  633. logGlobal->error("Stray map object that isn't fading");
  634. continue;
  635. }
  636. if (!canDrawObject(obj))
  637. continue;
  638. uint8_t animationFrame;
  639. if(obj->ID == Obj::HERO) //non-generic animation frame pick for hero and boat
  640. animationFrame = info->heroAnim;
  641. else
  642. animationFrame = info->anim;
  643. auto objData = findObjectBitmap(obj, animationFrame);
  644. if (objData.objBitmap)
  645. {
  646. Rect srcRect(object.rect.x, object.rect.y, tileSize, tileSize);
  647. drawObject(targetSurf, objData.objBitmap, &srcRect, objData.isMoving);
  648. if (objData.flagBitmap)
  649. {
  650. if (objData.isMoving)
  651. {
  652. srcRect.y += FRAMES_PER_MOVE_ANIM_GROUP * 2 - tileSize;
  653. Rect dstRect(realPos.x, realPos.y - tileSize / 2, tileSize, tileSize);
  654. drawHeroFlag(targetSurf, objData.flagBitmap, &srcRect, &dstRect, true);
  655. }
  656. else if (obj->pos.x == pos.x && obj->pos.y == pos.y)
  657. {
  658. Rect dstRect(realPos.x - 2 * tileSize, realPos.y - tileSize, 3 * tileSize, 2 * tileSize);
  659. drawHeroFlag(targetSurf, objData.flagBitmap, nullptr, &dstRect, false);
  660. }
  661. }
  662. }
  663. }
  664. }
  665. void CMapHandler::CMapBlitter::drawRoad(SDL_Surface * targetSurf, const TerrainTile & tinfo, const TerrainTile * tinfoUpper) const
  666. {
  667. if (tinfoUpper && tinfoUpper->roadType->getId() != Road::NO_ROAD)
  668. {
  669. ui8 rotation = (tinfoUpper->extTileFlags >> 4) % 4;
  670. Rect source(0, tileSize / 2, tileSize, tileSize / 2);
  671. Rect dest(realPos.x, realPos.y, tileSize, tileSize / 2);
  672. drawElement(EMapCacheType::ROADS, parent->roadImages[tinfoUpper->roadType->getJsonKey()][tinfoUpper->roadDir][rotation],
  673. &source, targetSurf, &dest);
  674. }
  675. if(tinfo.roadType->getId() != Road::NO_ROAD) //print road from this tile
  676. {
  677. ui8 rotation = (tinfo.extTileFlags >> 4) % 4;
  678. Rect source(0, 0, tileSize, halfTileSizeCeil);
  679. Rect dest(realPos.x, realPos.y + tileSize / 2, tileSize, tileSize / 2);
  680. drawElement(EMapCacheType::ROADS, parent->roadImages[tinfo.roadType->getJsonKey()][tinfo.roadDir][rotation],
  681. &source, targetSurf, &dest);
  682. }
  683. }
  684. void CMapHandler::CMapBlitter::drawRiver(SDL_Surface * targetSurf, const TerrainTile & tinfo) const
  685. {
  686. Rect destRect(realTileRect);
  687. ui8 rotation = (tinfo.extTileFlags >> 2) % 4;
  688. drawElement(EMapCacheType::RIVERS, parent->riverImages[tinfo.riverType->getJsonKey()][tinfo.riverDir][rotation], nullptr, targetSurf, &destRect);
  689. }
  690. void CMapHandler::CMapBlitter::drawFow(SDL_Surface * targetSurf) const
  691. {
  692. const NeighborTilesInfo neighborInfo(pos, parent->sizes, info->visibilityMap);
  693. int retBitmapID = neighborInfo.getBitmapID();// >=0 -> partial hide, <0 - full hide
  694. if (retBitmapID < 0)
  695. retBitmapID = - parent->hideBitmap[pos.z][pos.x][pos.y] - 1; //fully hidden
  696. std::shared_ptr<IImage> image;
  697. if (retBitmapID >= 0)
  698. image = parent->FoWpartialHide.at(retBitmapID);
  699. else
  700. image = parent->FoWfullHide.at(-retBitmapID - 1);
  701. Rect destRect(realTileRect);
  702. drawElement(EMapCacheType::FOW, image, nullptr, targetSurf, &destRect);
  703. }
  704. void CMapHandler::CMapBlitter::blit(SDL_Surface * targetSurf, const MapDrawingInfo * info)
  705. {
  706. init(info);
  707. auto prevClip = clip(targetSurf);
  708. pos = int3(0, 0, topTile.z);
  709. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  710. {
  711. if (pos.x < 0 || pos.x >= parent->sizes.x)
  712. continue;
  713. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  714. {
  715. if (pos.y < 0 || pos.y >= parent->sizes.y)
  716. continue;
  717. const bool isVisible = canDrawCurrentTile();
  718. realTileRect.x = realPos.x;
  719. realTileRect.y = realPos.y;
  720. const TerrainTile2 & tile = parent->ttiles[pos.z][pos.x][pos.y];
  721. const TerrainTile & tinfo = parent->map->getTile(pos);
  722. const TerrainTile * tinfoUpper = pos.y > 0 ? &parent->map->getTile(int3(pos.x, pos.y - 1, pos.z)) : nullptr;
  723. if(isVisible || info->showAllTerrain)
  724. {
  725. drawTileTerrain(targetSurf, tinfo, tile);
  726. if(tinfo.riverType->getId() != River::NO_RIVER)
  727. drawRiver(targetSurf, tinfo);
  728. drawRoad(targetSurf, tinfo, tinfoUpper);
  729. }
  730. if(isVisible)
  731. drawObjects(targetSurf, tile);
  732. }
  733. }
  734. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  735. {
  736. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  737. {
  738. realTileRect.x = realPos.x;
  739. realTileRect.y = realPos.y;
  740. if (pos.x < 0 || pos.x >= parent->sizes.x ||
  741. pos.y < 0 || pos.y >= parent->sizes.y)
  742. {
  743. drawFrame(targetSurf);
  744. }
  745. else
  746. {
  747. const TerrainTile2 & tile = parent->ttiles[pos.z][pos.x][pos.y];
  748. if(!settings["session"]["spectate"].Bool() && !(*info->visibilityMap)[topTile.z][pos.x][pos.y] && !info->showAllTerrain)
  749. drawFow(targetSurf);
  750. // overlay needs to be drawn over fow, because of artifacts-aura-like spells
  751. drawTileOverlay(targetSurf, tile);
  752. // drawDebugVisitables()
  753. if (settings["session"]["showBlock"].Bool())
  754. {
  755. if(parent->map->getTile(int3(pos.x, pos.y, pos.z)).blocked) //temporary hiding blocked positions
  756. {
  757. static std::shared_ptr<IImage> block;
  758. if (!block)
  759. block = IImage::createFromFile("blocked");
  760. block->draw(targetSurf, realTileRect.x, realTileRect.y);
  761. }
  762. }
  763. if (settings["session"]["showVisit"].Bool())
  764. {
  765. if(parent->map->getTile(int3(pos.x, pos.y, pos.z)).visitable) //temporary hiding visitable positions
  766. {
  767. static std::shared_ptr<IImage> visit;
  768. if (!visit)
  769. visit = IImage::createFromFile("visitable");
  770. visit->draw(targetSurf, realTileRect.x, realTileRect.y);
  771. }
  772. }
  773. }
  774. }
  775. }
  776. drawOverlayEx(targetSurf);
  777. // drawDebugGrid()
  778. if (settings["session"]["showGrid"].Bool())
  779. {
  780. for (realPos.x = initPos.x, pos.x = topTile.x; pos.x < topTile.x + tileCount.x; pos.x++, realPos.x += tileSize)
  781. {
  782. for (realPos.y = initPos.y, pos.y = topTile.y; pos.y < topTile.y + tileCount.y; pos.y++, realPos.y += tileSize)
  783. {
  784. constexpr ColorRGBA color(0x55, 0x55, 0x55);
  785. if (realPos.y >= info->drawBounds.y &&
  786. realPos.y < info->drawBounds.y + info->drawBounds.h)
  787. for(int i = 0; i < tileSize; i++)
  788. if (realPos.x + i >= info->drawBounds.x &&
  789. realPos.x + i < info->drawBounds.x + info->drawBounds.w)
  790. CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x + i, realPos.y, color.r, color.g, color.b);
  791. if (realPos.x >= info->drawBounds.x &&
  792. realPos.x < info->drawBounds.x + info->drawBounds.w)
  793. for(int i = 0; i < tileSize; i++)
  794. if (realPos.y + i >= info->drawBounds.y &&
  795. realPos.y + i < info->drawBounds.y + info->drawBounds.h)
  796. CSDL_Ext::putPixelWithoutRefresh(targetSurf, realPos.x, realPos.y + i, color.r, color.g, color.b);
  797. }
  798. }
  799. }
  800. postProcessing(targetSurf);
  801. CSDL_Ext::setClipRect(targetSurf, prevClip);
  802. }
  803. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findHeroBitmap(const CGHeroInstance * hero, int anim) const
  804. {
  805. if(hero && hero->moveDir && hero->type) //it's hero or boat
  806. {
  807. if(hero->tempOwner >= PlayerColor::PLAYER_LIMIT) //Neutral hero?
  808. {
  809. logGlobal->error("A neutral hero (%s) at %s. Should not happen!", hero->getNameTranslated(), hero->pos.toString());
  810. return CMapHandler::AnimBitmapHolder();
  811. }
  812. //pick graphics of hero (or boat if hero is sailing)
  813. std::shared_ptr<CAnimation> animation;
  814. if (hero->boat)
  815. animation = graphics->boatAnimations[hero->boat->subID];
  816. else
  817. animation = graphics->heroAnimations[hero->appearance->animationFile];
  818. bool moving = !hero->isStanding;
  819. int group = getHeroFrameGroup(hero->moveDir, moving);
  820. if(animation->size(group) > 0)
  821. {
  822. int frame = anim % animation->size(group);
  823. auto heroImage = animation->getImage(frame, group);
  824. //get flag overlay only if we have main image
  825. auto flagImage = findFlagBitmap(hero, anim, &hero->tempOwner, group);
  826. return CMapHandler::AnimBitmapHolder(heroImage, flagImage, moving);
  827. }
  828. }
  829. return CMapHandler::AnimBitmapHolder();
  830. }
  831. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findBoatBitmap(const CGBoat * boat, int anim) const
  832. {
  833. auto animation = graphics->boatAnimations.at(boat->subID);
  834. int group = getHeroFrameGroup(boat->direction, false);
  835. if(animation->size(group) > 0)
  836. return CMapHandler::AnimBitmapHolder(animation->getImage(anim % animation->size(group), group));
  837. else
  838. return CMapHandler::AnimBitmapHolder();
  839. }
  840. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findFlagBitmap(const CGHeroInstance * hero, int anim, const PlayerColor * color, int group) const
  841. {
  842. if(!hero)
  843. return std::shared_ptr<IImage>();
  844. if(hero->boat)
  845. return findBoatFlagBitmap(hero->boat, anim, color, group, hero->moveDir);
  846. return findHeroFlagBitmap(hero, anim, color, group);
  847. }
  848. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findHeroFlagBitmap(const CGHeroInstance * hero, int anim, const PlayerColor * color, int group) const
  849. {
  850. return findFlagBitmapInternal(graphics->heroFlagAnimations.at(color->getNum()), anim, group, hero->moveDir, !hero->isStanding);
  851. }
  852. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findBoatFlagBitmap(const CGBoat * boat, int anim, const PlayerColor * color, int group, ui8 dir) const
  853. {
  854. int boatType = boat->subID;
  855. if(boatType < 0 || boatType >= graphics->boatFlagAnimations.size())
  856. {
  857. logGlobal->error("Not supported boat subtype: %d", boat->subID);
  858. return nullptr;
  859. }
  860. const auto & subtypeFlags = graphics->boatFlagAnimations.at(boatType);
  861. int colorIndex = color->getNum();
  862. if(colorIndex < 0 || colorIndex >= subtypeFlags.size())
  863. {
  864. logGlobal->error("Invalid player color %d", colorIndex);
  865. return nullptr;
  866. }
  867. return findFlagBitmapInternal(subtypeFlags.at(colorIndex), anim, group, dir, false);
  868. }
  869. std::shared_ptr<IImage> CMapHandler::CMapBlitter::findFlagBitmapInternal(std::shared_ptr<CAnimation> animation, int anim, int group, ui8 dir, bool moving) const
  870. {
  871. size_t groupSize = animation->size(group);
  872. if(groupSize == 0)
  873. return nullptr;
  874. if(moving)
  875. return animation->getImage(anim % groupSize, group);
  876. else
  877. return animation->getImage((anim / 4) % groupSize, group);
  878. }
  879. CMapHandler::AnimBitmapHolder CMapHandler::CMapBlitter::findObjectBitmap(const CGObjectInstance * obj, int anim) const
  880. {
  881. if (!obj)
  882. return CMapHandler::AnimBitmapHolder();
  883. if (obj->ID == Obj::HERO)
  884. return findHeroBitmap(static_cast<const CGHeroInstance*>(obj), anim);
  885. if (obj->ID == Obj::BOAT)
  886. return findBoatBitmap(static_cast<const CGBoat*>(obj), anim);
  887. // normal object
  888. std::shared_ptr<CAnimation> animation = graphics->getAnimation(obj);
  889. size_t groupSize = animation->size();
  890. if(groupSize == 0)
  891. return CMapHandler::AnimBitmapHolder();
  892. auto bitmap = animation->getImage((anim + getPhaseShift(obj)) % groupSize);
  893. if(!bitmap)
  894. return CMapHandler::AnimBitmapHolder();
  895. bitmap->setFlagColor(obj->tempOwner);
  896. return CMapHandler::AnimBitmapHolder(bitmap);
  897. }
  898. ui8 CMapHandler::CMapBlitter::getPhaseShift(const CGObjectInstance *object) const
  899. {
  900. auto i = parent->animationPhase.find(object);
  901. if(i == parent->animationPhase.end())
  902. {
  903. ui8 ret = CRandomGenerator::getDefault().nextInt(254);
  904. parent->animationPhase[object] = ret;
  905. return ret;
  906. }
  907. return i->second;
  908. }
  909. bool CMapHandler::CMapBlitter::canDrawObject(const CGObjectInstance * obj) const
  910. {
  911. //checking if object has non-empty graphic on this tile
  912. return obj->ID == Obj::HERO || obj->coveringAt(pos.x, pos.y);
  913. }
  914. bool CMapHandler::CMapBlitter::canDrawCurrentTile() const
  915. {
  916. if(settings["session"]["spectate"].Bool())
  917. return true;
  918. const NeighborTilesInfo neighbors(pos, parent->sizes, info->visibilityMap);
  919. return !neighbors.areAllHidden();
  920. }
  921. ui8 CMapHandler::CMapBlitter::getHeroFrameGroup(ui8 dir, bool isMoving) const
  922. {
  923. if(isMoving)
  924. {
  925. static const ui8 frame [] = {0xff, 10, 5, 6, 7, 8, 9, 12, 11};
  926. return frame[dir];
  927. }
  928. else //if(isMoving)
  929. {
  930. static const ui8 frame [] = {0xff, 13, 0, 1, 2, 3, 4, 15, 14};
  931. return frame[dir];
  932. }
  933. }
  934. bool CMapHandler::updateObjectsFade()
  935. {
  936. for (auto iter = fadeAnims.begin(); iter != fadeAnims.end(); )
  937. {
  938. int3 pos = (*iter).second.first;
  939. CFadeAnimation * anim = (*iter).second.second;
  940. anim->update();
  941. if (anim->isFading())
  942. ++iter;
  943. else // fade finished
  944. {
  945. auto &objs = ttiles[pos.z][pos.x][pos.y].objects;
  946. for (auto objIter = objs.begin(); objIter != objs.end(); ++objIter)
  947. {
  948. if ((*objIter).fadeAnimKey == (*iter).first)
  949. {
  950. logAnim->trace("Fade anim finished for obj at %s; remaining: %d", pos.toString(), fadeAnims.size() - 1);
  951. if (anim->fadingMode == CFadeAnimation::EMode::OUT)
  952. objs.erase(objIter); // if this was fadeout, remove the object from the map
  953. else
  954. (*objIter).fadeAnimKey = -1; // for fadein, just remove its connection to the finished fade
  955. break;
  956. }
  957. }
  958. delete (*iter).second.second;
  959. iter = fadeAnims.erase(iter);
  960. }
  961. }
  962. return !fadeAnims.empty();
  963. }
  964. bool CMapHandler::startObjectFade(TerrainTileObject & obj, bool in, int3 pos)
  965. {
  966. SDL_Surface * fadeBitmap;
  967. assert(obj.obj);
  968. auto objData = normalBlitter->findObjectBitmap(obj.obj, 0);
  969. if (objData.objBitmap)
  970. {
  971. if (objData.isMoving) // ignore fading of moving objects (for now?)
  972. {
  973. logAnim->debug("Ignoring fade of moving object");
  974. return false;
  975. }
  976. fadeBitmap = CSDL_Ext::newSurface(32, 32); // TODO cache these bitmaps instead of creating new ones?
  977. Rect objSrcRect(obj.rect.x, obj.rect.y, 32, 32);
  978. objData.objBitmap->draw(fadeBitmap,0,0,&objSrcRect);
  979. if (objData.flagBitmap)
  980. {
  981. if (obj.obj->pos.x - 1 == pos.x && obj.obj->pos.y - 1 == pos.y) // -1 to draw flag in top-center instead of right-bottom; kind of a hack
  982. {
  983. Rect flagSrcRect(32, 0, 32, 32);
  984. objData.flagBitmap->draw(fadeBitmap,0,0, &flagSrcRect);
  985. }
  986. }
  987. auto anim = new CFadeAnimation();
  988. anim->init(in ? CFadeAnimation::EMode::IN : CFadeAnimation::EMode::OUT, fadeBitmap, true);
  989. fadeAnims[++fadeAnimCounter] = std::pair<int3, CFadeAnimation*>(pos, anim);
  990. obj.fadeAnimKey = fadeAnimCounter;
  991. logAnim->trace("Fade anim started for obj %d at %s; anim count: %d", obj.obj->ID, pos.toString(), fadeAnims.size());
  992. return true;
  993. }
  994. return false;
  995. }
  996. bool CMapHandler::printObject(const CGObjectInstance * obj, bool fadein)
  997. {
  998. auto animation = graphics->getAnimation(obj);
  999. if(!animation)
  1000. return false;
  1001. auto bitmap = animation->getImage(0);
  1002. if(!bitmap)
  1003. return false;
  1004. const int tilesW = bitmap->width()/32;
  1005. const int tilesH = bitmap->height()/32;
  1006. auto ttilesWidth = ttiles.shape()[1];
  1007. auto ttilesHeight = ttiles.shape()[2];
  1008. for(int fx=0; fx<tilesW; ++fx)
  1009. {
  1010. for(int fy=0; fy<tilesH; ++fy)
  1011. {
  1012. Rect cr;
  1013. cr.w = 32;
  1014. cr.h = 32;
  1015. cr.x = fx*32;
  1016. cr.y = fy*32;
  1017. if((obj->pos.x + fx - tilesW + 1) >= 0 &&
  1018. (obj->pos.x + fx - tilesW + 1) < ttilesWidth - frameW &&
  1019. (obj->pos.y + fy - tilesH + 1) >= 0 &&
  1020. (obj->pos.y + fy - tilesH + 1) < ttilesHeight - frameH)
  1021. {
  1022. int3 pos(obj->pos.x + fx - tilesW + 1, obj->pos.y + fy - tilesH + 1, obj->pos.z);
  1023. TerrainTile2 & curt = ttiles[pos.z][pos.x][pos.y];
  1024. TerrainTileObject toAdd(obj, cr, obj->visitableAt(pos.x, pos.y));
  1025. if (fadein && ADVOPT.objectFading)
  1026. {
  1027. startObjectFade(toAdd, true, pos);
  1028. }
  1029. auto i = curt.objects.begin();
  1030. for(; i != curt.objects.end(); i++)
  1031. {
  1032. if(objectBlitOrderSorter(toAdd, *i))
  1033. {
  1034. curt.objects.insert(i, toAdd);
  1035. i = curt.objects.begin(); //to validate and avoid adding it second time
  1036. break;
  1037. }
  1038. }
  1039. if(i == curt.objects.end())
  1040. curt.objects.insert(i, toAdd);
  1041. }
  1042. }
  1043. }
  1044. return true;
  1045. }
  1046. bool CMapHandler::hideObject(const CGObjectInstance * obj, bool fadeout)
  1047. {
  1048. for(size_t z = 0; z < map->levels(); z++)
  1049. {
  1050. for(size_t x = 0; x < map->width; x++)
  1051. {
  1052. for(size_t y = 0; y < map->height; y++)
  1053. {
  1054. auto &objs = ttiles[(int)z][(int)x][(int)y].objects;
  1055. for(size_t i = 0; i < objs.size(); i++)
  1056. {
  1057. if (objs[i].obj && objs[i].obj->id == obj->id)
  1058. {
  1059. if (fadeout && ADVOPT.objectFading) // object should be faded == erase is delayed until the end of fadeout
  1060. {
  1061. if (startObjectFade(objs[i], false, int3((si32)x, (si32)y, (si32)z)))
  1062. objs[i].obj = nullptr;
  1063. else
  1064. objs.erase(objs.begin() + i);
  1065. }
  1066. else
  1067. objs.erase(objs.begin() + i);
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. return true;
  1075. }
  1076. bool CMapHandler::canStartHeroMovement()
  1077. {
  1078. return fadeAnims.empty(); // don't allow movement during fade animation
  1079. }
  1080. void CMapHandler::updateWater() //shift colors in palettes of water tiles
  1081. {
  1082. for(auto & elem : terrainImages["lava"])
  1083. {
  1084. for(auto img : elem)
  1085. img->shiftPalette(246, 9);
  1086. }
  1087. for(auto & elem : terrainImages["water"])
  1088. {
  1089. for(auto img : elem)
  1090. {
  1091. img->shiftPalette(229, 12);
  1092. img->shiftPalette(242, 14);
  1093. }
  1094. }
  1095. for(auto & elem : riverImages["clrrvr"])
  1096. {
  1097. for(auto img : elem)
  1098. {
  1099. img->shiftPalette(183, 12);
  1100. img->shiftPalette(195, 6);
  1101. }
  1102. }
  1103. for(auto & elem : riverImages["mudrvr"])
  1104. {
  1105. for(auto img : elem)
  1106. {
  1107. img->shiftPalette(228, 12);
  1108. img->shiftPalette(183, 6);
  1109. img->shiftPalette(240, 6);
  1110. }
  1111. }
  1112. for(auto & elem : riverImages["lavrvr"])
  1113. {
  1114. for(auto img : elem)
  1115. img->shiftPalette(240, 9);
  1116. }
  1117. }
  1118. CMapHandler::~CMapHandler()
  1119. {
  1120. delete normalBlitter;
  1121. delete worldViewBlitter;
  1122. delete puzzleViewBlitter;
  1123. for (auto & elem : fadeAnims)
  1124. {
  1125. delete elem.second.second;
  1126. }
  1127. }
  1128. CMapHandler::CMapHandler()
  1129. {
  1130. frameW = frameH = 0;
  1131. normalBlitter = new CMapNormalBlitter(this);
  1132. worldViewBlitter = new CMapWorldViewBlitter(this);
  1133. puzzleViewBlitter = new CMapPuzzleViewBlitter(this);
  1134. fadeAnimCounter = 0;
  1135. map = nullptr;
  1136. tilesW = tilesH = 0;
  1137. offsetX = offsetY = 0;
  1138. egdeAnimation = std::make_unique<CAnimation>("EDG");
  1139. egdeAnimation->preload();
  1140. }
  1141. bool CMapHandler::hasObjectHole(const int3 & pos) const
  1142. {
  1143. const TerrainTile2 & tt = ttiles[pos.z][pos.x][pos.y];
  1144. for(auto & elem : tt.objects)
  1145. {
  1146. if(elem.obj && elem.obj->ID == Obj::HOLE)
  1147. return true;
  1148. }
  1149. return false;
  1150. }
  1151. void CMapHandler::getTerrainDescr(const int3 & pos, std::string & out, bool isRMB) const
  1152. {
  1153. const TerrainTile & t = map->getTile(pos);
  1154. if(t.hasFavorableWinds())
  1155. {
  1156. out = CGI->objtypeh->getObjectName(Obj::FAVORABLE_WINDS, 0);
  1157. return;
  1158. }
  1159. const TerrainTile2 & tt = ttiles[pos.z][pos.x][pos.y];
  1160. bool isTile2Terrain = false;
  1161. out.clear();
  1162. for(auto & elem : tt.objects)
  1163. {
  1164. if(elem.obj)
  1165. {
  1166. out = elem.obj->getObjectName();
  1167. if(elem.obj->ID == Obj::HOLE)
  1168. return;
  1169. isTile2Terrain = elem.obj->isTile2Terrain();
  1170. break;
  1171. }
  1172. }
  1173. if(!isTile2Terrain || out.empty())
  1174. out = t.terType->getNameTranslated();
  1175. if(t.getDiggingStatus(false) == EDiggingStatus::CAN_DIG)
  1176. {
  1177. out = boost::str(boost::format(isRMB ? "%s\r\n%s" : "%s %s") // New line for the Message Box, space for the Status Bar
  1178. % out
  1179. % CGI->generaltexth->allTexts[330]); // 'digging ok'
  1180. }
  1181. }
  1182. void CMapHandler::discardWorldViewCache()
  1183. {
  1184. cache.discardWorldViewCache();
  1185. }
  1186. CMapHandler::CMapCache::CMapCache()
  1187. {
  1188. worldViewCachedScale = 0;
  1189. }
  1190. void CMapHandler::CMapCache::discardWorldViewCache()
  1191. {
  1192. for(auto & cache : data)
  1193. cache.clear();
  1194. logAnim->debug("Discarded world view cache");
  1195. }
  1196. void CMapHandler::CMapCache::updateWorldViewScale(float scale)
  1197. {
  1198. if (fabs(scale - worldViewCachedScale) > 0.001f)
  1199. discardWorldViewCache();
  1200. worldViewCachedScale = scale;
  1201. }
  1202. std::shared_ptr<IImage> CMapHandler::CMapCache::requestWorldViewCacheOrCreate(CMapHandler::EMapCacheType type, std::shared_ptr<IImage> fullSurface)
  1203. {
  1204. intptr_t key = (intptr_t) (fullSurface.get());
  1205. auto & cache = data[(ui8)type];
  1206. auto iter = cache.find(key);
  1207. if(iter == cache.end())
  1208. {
  1209. auto scaled = fullSurface->scaleFast(fullSurface->dimensions() * worldViewCachedScale);
  1210. cache[key] = scaled;
  1211. return scaled;
  1212. }
  1213. else
  1214. {
  1215. return (*iter).second;
  1216. }
  1217. }
  1218. bool CMapHandler::compareObjectBlitOrder(const CGObjectInstance * a, const CGObjectInstance * b)
  1219. {
  1220. if (!a)
  1221. return true;
  1222. if (!b)
  1223. return false;
  1224. if (a->appearance->printPriority != b->appearance->printPriority)
  1225. return a->appearance->printPriority > b->appearance->printPriority;
  1226. if(a->pos.y != b->pos.y)
  1227. return a->pos.y < b->pos.y;
  1228. if(b->ID==Obj::HERO && a->ID!=Obj::HERO)
  1229. return true;
  1230. if(b->ID!=Obj::HERO && a->ID==Obj::HERO)
  1231. return false;
  1232. if(!a->isVisitable() && b->isVisitable())
  1233. return true;
  1234. if(!b->isVisitable() && a->isVisitable())
  1235. return false;
  1236. if(a->pos.x < b->pos.x)
  1237. return true;
  1238. return false;
  1239. }
  1240. TerrainTileObject::TerrainTileObject(const CGObjectInstance * obj_, Rect rect_, bool visitablePos)
  1241. : obj(obj_),
  1242. rect(rect_),
  1243. fadeAnimKey(-1)
  1244. {
  1245. // We store information about ambient sound is here because object might disappear while sound is updating
  1246. if(obj->getAmbientSound())
  1247. {
  1248. // All tiles of static objects are sound sources. E.g Volcanos and special terrains
  1249. // For visitable object only their visitable tile is sound source
  1250. if(!CCS->soundh->ambientCheckVisitable() || !obj->isVisitable() || visitablePos)
  1251. ambientSound = obj->getAmbientSound();
  1252. }
  1253. }
  1254. TerrainTileObject::~TerrainTileObject()
  1255. {
  1256. }