mapHandler.cpp 47 KB

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