mapHandler.cpp 45 KB

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