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