mapHandler.cpp 45 KB

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