mapHandler.cpp 45 KB

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