mapHandler.cpp 45 KB

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