Image.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "Context.h"
  24. #include "Decompress.h"
  25. #include "File.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include <cstdlib>
  30. #include <cstring>
  31. #include <stb_image.h>
  32. #include <stb_image_write.h>
  33. #include <jo_jpeg.h>
  34. #include <SDL_surface.h>
  35. #include "DebugNew.h"
  36. extern "C" unsigned char *stbi_write_png_to_mem(unsigned char *pixels, int stride_bytes, int x, int y, int n, int *out_len);
  37. #ifndef MAKEFOURCC
  38. #define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
  39. #endif
  40. #define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
  41. #define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
  42. #define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
  43. #define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
  44. #define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
  45. namespace Urho3D
  46. {
  47. /// DirectDraw color key definition.
  48. struct DDColorKey
  49. {
  50. unsigned dwColorSpaceLowValue_;
  51. unsigned dwColorSpaceHighValue_;
  52. };
  53. /// DirectDraw pixel format definition.
  54. struct DDPixelFormat
  55. {
  56. unsigned dwSize_;
  57. unsigned dwFlags_;
  58. unsigned dwFourCC_;
  59. union
  60. {
  61. unsigned dwRGBBitCount_;
  62. unsigned dwYUVBitCount_;
  63. unsigned dwZBufferBitDepth_;
  64. unsigned dwAlphaBitDepth_;
  65. unsigned dwLuminanceBitCount_;
  66. unsigned dwBumpBitCount_;
  67. unsigned dwPrivateFormatBitCount_;
  68. };
  69. union
  70. {
  71. unsigned dwRBitMask_;
  72. unsigned dwYBitMask_;
  73. unsigned dwStencilBitDepth_;
  74. unsigned dwLuminanceBitMask_;
  75. unsigned dwBumpDuBitMask_;
  76. unsigned dwOperations_;
  77. };
  78. union
  79. {
  80. unsigned dwGBitMask_;
  81. unsigned dwUBitMask_;
  82. unsigned dwZBitMask_;
  83. unsigned dwBumpDvBitMask_;
  84. struct
  85. {
  86. unsigned short wFlipMSTypes_;
  87. unsigned short wBltMSTypes_;
  88. } multiSampleCaps_;
  89. };
  90. union
  91. {
  92. unsigned dwBBitMask_;
  93. unsigned dwVBitMask_;
  94. unsigned dwStencilBitMask_;
  95. unsigned dwBumpLuminanceBitMask_;
  96. };
  97. union
  98. {
  99. unsigned dwRGBAlphaBitMask_;
  100. unsigned dwYUVAlphaBitMask_;
  101. unsigned dwLuminanceAlphaBitMask_;
  102. unsigned dwRGBZBitMask_;
  103. unsigned dwYUVZBitMask_;
  104. };
  105. };
  106. /// DirectDraw surface capabilities.
  107. struct DDSCaps2
  108. {
  109. unsigned dwCaps_;
  110. unsigned dwCaps2_;
  111. unsigned dwCaps3_;
  112. union
  113. {
  114. unsigned dwCaps4_;
  115. unsigned dwVolumeDepth_;
  116. };
  117. };
  118. /// DirectDraw surface description.
  119. struct DDSurfaceDesc2
  120. {
  121. unsigned dwSize_;
  122. unsigned dwFlags_;
  123. unsigned dwHeight_;
  124. unsigned dwWidth_;
  125. union
  126. {
  127. unsigned lPitch_;
  128. unsigned dwLinearSize_;
  129. };
  130. union
  131. {
  132. unsigned dwBackBufferCount_;
  133. unsigned dwDepth_;
  134. };
  135. union
  136. {
  137. unsigned dwMipMapCount_;
  138. unsigned dwRefreshRate_;
  139. unsigned dwSrcVBHandle_;
  140. };
  141. unsigned dwAlphaBitDepth_;
  142. unsigned dwReserved_;
  143. unsigned lpSurface_; // Do not define as a void pointer, as it is 8 bytes in a 64bit build
  144. union
  145. {
  146. DDColorKey ddckCKDestOverlay_;
  147. unsigned dwEmptyFaceColor_;
  148. };
  149. DDColorKey ddckCKDestBlt_;
  150. DDColorKey ddckCKSrcOverlay_;
  151. DDColorKey ddckCKSrcBlt_;
  152. union
  153. {
  154. DDPixelFormat ddpfPixelFormat_;
  155. unsigned dwFVF_;
  156. };
  157. DDSCaps2 ddsCaps_;
  158. unsigned dwTextureStage_;
  159. };
  160. bool CompressedLevel::Decompress(unsigned char* dest)
  161. {
  162. if (!data_)
  163. return false;
  164. switch (format_)
  165. {
  166. case CF_DXT1:
  167. case CF_DXT3:
  168. case CF_DXT5:
  169. DecompressImageDXT(dest, data_, width_, height_, depth_, format_);
  170. return true;
  171. case CF_ETC1:
  172. DecompressImageETC(dest, data_, width_, height_);
  173. return true;
  174. case CF_PVRTC_RGB_2BPP:
  175. case CF_PVRTC_RGBA_2BPP:
  176. case CF_PVRTC_RGB_4BPP:
  177. case CF_PVRTC_RGBA_4BPP:
  178. DecompressImagePVRTC(dest, data_, width_, height_, format_);
  179. return true;
  180. default:
  181. // Unknown format
  182. return false;
  183. }
  184. }
  185. Image::Image(Context* context) :
  186. Resource(context),
  187. width_(0),
  188. height_(0),
  189. depth_(0),
  190. components_(0)
  191. {
  192. }
  193. Image::~Image()
  194. {
  195. }
  196. void Image::RegisterObject(Context* context)
  197. {
  198. context->RegisterFactory<Image>();
  199. }
  200. bool Image::BeginLoad(Deserializer& source)
  201. {
  202. // Check for DDS, KTX or PVR compressed format
  203. String fileID = source.ReadFileID();
  204. if (fileID == "DDS ")
  205. {
  206. // DDS compressed format
  207. DDSurfaceDesc2 ddsd;
  208. source.Read(&ddsd, sizeof(ddsd));
  209. switch (ddsd.ddpfPixelFormat_.dwFourCC_)
  210. {
  211. case FOURCC_DXT1:
  212. compressedFormat_ = CF_DXT1;
  213. components_ = 3;
  214. break;
  215. case FOURCC_DXT3:
  216. compressedFormat_ = CF_DXT3;
  217. components_ = 4;
  218. break;
  219. case FOURCC_DXT5:
  220. compressedFormat_ = CF_DXT5;
  221. components_ = 4;
  222. break;
  223. default:
  224. LOGERROR("Unsupported DDS format");
  225. return false;
  226. }
  227. unsigned dataSize = source.GetSize() - source.GetPosition();
  228. data_ = new unsigned char[dataSize];
  229. width_ = ddsd.dwWidth_;
  230. height_ = ddsd.dwHeight_;
  231. depth_ = ddsd.dwDepth_;
  232. numCompressedLevels_ = ddsd.dwMipMapCount_;
  233. if (!numCompressedLevels_)
  234. numCompressedLevels_ = 1;
  235. SetMemoryUse(dataSize);
  236. source.Read(data_.Get(), dataSize);
  237. }
  238. else if (fileID == "\253KTX")
  239. {
  240. source.Seek(12);
  241. unsigned endianness = source.ReadUInt();
  242. unsigned type = source.ReadUInt();
  243. /* unsigned typeSize = */ source.ReadUInt();
  244. unsigned format = source.ReadUInt();
  245. unsigned internalFormat = source.ReadUInt();
  246. /* unsigned baseInternalFormat = */ source.ReadUInt();
  247. unsigned width = source.ReadUInt();
  248. unsigned height = source.ReadUInt();
  249. unsigned depth = source.ReadUInt();
  250. /* unsigned arrayElements = */ source.ReadUInt();
  251. unsigned faces = source.ReadUInt();
  252. unsigned mipmaps = source.ReadUInt();
  253. unsigned keyValueBytes = source.ReadUInt();
  254. if (endianness != 0x04030201)
  255. {
  256. LOGERROR("Big-endian KTX files not supported");
  257. return false;
  258. }
  259. if (type != 0 || format != 0)
  260. {
  261. LOGERROR("Uncompressed KTX files not supported");
  262. return false;
  263. }
  264. if (faces > 1 || depth > 1)
  265. {
  266. LOGERROR("3D or cube KTX files not supported");
  267. return false;
  268. }
  269. if (mipmaps == 0)
  270. {
  271. LOGERROR("KTX files without explicitly specified mipmap count not supported");
  272. return false;
  273. }
  274. compressedFormat_ = CF_NONE;
  275. switch (internalFormat)
  276. {
  277. case 0x83f1:
  278. compressedFormat_ = CF_DXT1;
  279. components_ = 4;
  280. break;
  281. case 0x83f2:
  282. compressedFormat_ = CF_DXT3;
  283. components_ = 4;
  284. break;
  285. case 0x83f3:
  286. compressedFormat_ = CF_DXT5;
  287. components_ = 4;
  288. break;
  289. case 0x8d64:
  290. compressedFormat_ = CF_ETC1;
  291. components_ = 3;
  292. break;
  293. case 0x8c00:
  294. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  295. components_ = 3;
  296. break;
  297. case 0x8c01:
  298. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  299. components_ = 3;
  300. break;
  301. case 0x8c02:
  302. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  303. components_ = 4;
  304. break;
  305. case 0x8c03:
  306. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  307. components_ = 4;
  308. break;
  309. }
  310. if (compressedFormat_ == CF_NONE)
  311. {
  312. LOGERROR("Unsupported texture format in KTX file");
  313. return false;
  314. }
  315. source.Seek(source.GetPosition() + keyValueBytes);
  316. unsigned dataSize = source.GetSize() - source.GetPosition() - mipmaps * sizeof(unsigned);
  317. data_ = new unsigned char[dataSize];
  318. width_ = width;
  319. height_ = height;
  320. numCompressedLevels_ = mipmaps;
  321. unsigned dataOffset = 0;
  322. for (unsigned i = 0; i < mipmaps; ++i)
  323. {
  324. unsigned levelSize = source.ReadUInt();
  325. if (levelSize + dataOffset > dataSize)
  326. {
  327. LOGERROR("KTX mipmap level data size exceeds file size");
  328. return false;
  329. }
  330. source.Read(&data_[dataOffset], levelSize);
  331. dataOffset += levelSize;
  332. if (source.GetPosition() & 3)
  333. source.Seek((source.GetPosition() + 3) & 0xfffffffc);
  334. }
  335. SetMemoryUse(dataSize);
  336. }
  337. else if (fileID == "PVR\3")
  338. {
  339. /* unsigned flags = */ source.ReadUInt();
  340. unsigned pixelFormatLo = source.ReadUInt();
  341. /* unsigned pixelFormatHi = */ source.ReadUInt();
  342. /* unsigned colourSpace = */ source.ReadUInt();
  343. /* unsigned channelType = */ source.ReadUInt();
  344. unsigned height = source.ReadUInt();
  345. unsigned width = source.ReadUInt();
  346. unsigned depth = source.ReadUInt();
  347. /* unsigned numSurfaces = */ source.ReadUInt();
  348. unsigned numFaces = source.ReadUInt();
  349. unsigned mipmapCount = source.ReadUInt();
  350. unsigned metaDataSize = source.ReadUInt();
  351. if (depth > 1 || numFaces > 1)
  352. {
  353. LOGERROR("3D or cube PVR files not supported");
  354. return false;
  355. }
  356. if (mipmapCount == 0)
  357. {
  358. LOGERROR("PVR files without explicitly specified mipmap count not supported");
  359. return false;
  360. }
  361. compressedFormat_ = CF_NONE;
  362. switch (pixelFormatLo)
  363. {
  364. case 0:
  365. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  366. components_ = 3;
  367. break;
  368. case 1:
  369. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  370. components_ = 4;
  371. break;
  372. case 2:
  373. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  374. components_ = 3;
  375. break;
  376. case 3:
  377. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  378. components_ = 4;
  379. break;
  380. case 6:
  381. compressedFormat_ = CF_ETC1;
  382. components_ = 3;
  383. break;
  384. case 7:
  385. compressedFormat_ = CF_DXT1;
  386. components_ = 4;
  387. break;
  388. case 9:
  389. compressedFormat_ = CF_DXT3;
  390. components_ = 4;
  391. break;
  392. case 11:
  393. compressedFormat_ = CF_DXT5;
  394. components_ = 4;
  395. break;
  396. }
  397. if (compressedFormat_ == CF_NONE)
  398. {
  399. LOGERROR("Unsupported texture format in PVR file");
  400. return false;
  401. }
  402. source.Seek(source.GetPosition() + metaDataSize);
  403. unsigned dataSize = source.GetSize() - source.GetPosition();
  404. data_ = new unsigned char[dataSize];
  405. width_ = width;
  406. height_ = height;
  407. numCompressedLevels_ = mipmapCount;
  408. source.Read(data_.Get(), dataSize);
  409. SetMemoryUse(dataSize);
  410. }
  411. else
  412. {
  413. // Not DDS, KTX or PVR, use STBImage to load other image formats as uncompressed
  414. source.Seek(0);
  415. int width, height;
  416. unsigned components;
  417. unsigned char* pixelData = GetImageData(source, width, height, components);
  418. if (!pixelData)
  419. {
  420. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  421. return false;
  422. }
  423. SetSize(width, height, components);
  424. SetData(pixelData);
  425. FreeImageData(pixelData);
  426. }
  427. return true;
  428. }
  429. bool Image::Save(Serializer& dest) const
  430. {
  431. PROFILE(SaveImage);
  432. if (IsCompressed())
  433. {
  434. LOGERROR("Can not save compressed image " + GetName());
  435. return false;
  436. }
  437. if (!data_)
  438. {
  439. LOGERROR("Can not save zero-sized image " + GetName());
  440. return false;
  441. }
  442. int len;
  443. unsigned char *png = stbi_write_png_to_mem(data_.Get(), 0, width_, height_, components_, &len);
  444. bool success = dest.Write(png, len) == (unsigned)len;
  445. free(png);
  446. return success;
  447. }
  448. bool Image::SetSize(int width, int height, unsigned components)
  449. {
  450. return SetSize(width, height, 1, components);
  451. }
  452. bool Image::SetSize(int width, int height, int depth, unsigned components)
  453. {
  454. if (width == width_ && height == height_ && depth == depth_ && components == components_)
  455. return true;
  456. if (width <= 0 || height <= 0 || depth <= 0)
  457. return false;
  458. if (components > 4)
  459. {
  460. LOGERROR("More than 4 color components are not supported");
  461. return false;
  462. }
  463. data_ = new unsigned char[width * height * depth * components];
  464. width_ = width;
  465. height_ = height;
  466. depth_ = depth;
  467. components_ = components;
  468. compressedFormat_ = CF_NONE;
  469. numCompressedLevels_ = 0;
  470. nextLevel_.Reset();
  471. SetMemoryUse(width * height * depth * components);
  472. return true;
  473. }
  474. void Image::SetPixel(int x, int y, const Color& color)
  475. {
  476. SetPixelInt(x, y, 0, color.ToUInt());
  477. }
  478. void Image::SetPixel(int x, int y, int z, const Color& color)
  479. {
  480. SetPixelInt(x, y, z, color.ToUInt());
  481. }
  482. void Image::SetPixelInt(int x, int y, unsigned uintColor)
  483. {
  484. SetPixelInt(x, y, 0, uintColor);
  485. }
  486. void Image::SetPixelInt(int x, int y, int z, unsigned uintColor)
  487. {
  488. if (!data_ || x < 0 || x >= width_ || y < 0 || y >= height_ || z < 0 || z >= depth_ || IsCompressed())
  489. return;
  490. unsigned char* dest = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  491. unsigned char* src = (unsigned char*)&uintColor;
  492. switch (components_)
  493. {
  494. case 4:
  495. dest[3] = src[3];
  496. // Fall through
  497. case 3:
  498. dest[2] = src[2];
  499. // Fall through
  500. case 2:
  501. dest[1]= src[1];
  502. // Fall through
  503. default:
  504. dest[0] = src[0];
  505. break;
  506. }
  507. }
  508. void Image::SetData(const unsigned char* pixelData)
  509. {
  510. if (!data_)
  511. return;
  512. if (IsCompressed())
  513. {
  514. LOGERROR("Can not set new pixel data for a compressed image");
  515. return;
  516. }
  517. memcpy(data_.Get(), pixelData, width_ * height_ * depth_ * components_);
  518. nextLevel_.Reset();
  519. }
  520. bool Image::LoadColorLUT(Deserializer& source)
  521. {
  522. String fileID = source.ReadFileID();
  523. if (fileID == "DDS " || fileID == "\253KTX" || fileID == "PVR\3")
  524. {
  525. LOGERROR("Invalid image format, can not load image");
  526. return false;
  527. }
  528. source.Seek(0);
  529. int width, height;
  530. unsigned components;
  531. unsigned char* pixelDataIn = GetImageData(source, width, height, components);
  532. if (!pixelDataIn)
  533. {
  534. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  535. return false;
  536. }
  537. if (components != 3)
  538. {
  539. LOGERROR("Invalid image format, can not load image");
  540. return false;
  541. }
  542. SetSize(COLOR_LUT_SIZE, COLOR_LUT_SIZE, COLOR_LUT_SIZE, components);
  543. SetMemoryUse(width_ * height_ * depth_ * components);
  544. unsigned char* pixelDataOut = GetData();
  545. for (int z = 0; z < depth_; ++z)
  546. {
  547. for (int y = 0; y < height_; ++y)
  548. {
  549. unsigned char* in = &pixelDataIn[z * width_ * 3 + y * width * 3];
  550. unsigned char* out = &pixelDataOut[z * width_ * height_ * 3 + y * width_ * 3];
  551. for (int x = 0; x < width_ * 3; x += 3)
  552. {
  553. out[x] = in[x];
  554. out[x+1] = in[x + 1];
  555. out[x+2] = in[x + 2];
  556. }
  557. }
  558. }
  559. FreeImageData(pixelDataIn);
  560. return true;
  561. }
  562. void Image::FlipVertical()
  563. {
  564. if (!data_)
  565. return;
  566. if (depth_ > 1)
  567. {
  568. LOGERROR("FlipVertical not supported for 3D images");
  569. return;
  570. }
  571. if (!IsCompressed())
  572. {
  573. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  574. unsigned rowSize = width_ * components_;
  575. for (int y = 0; y < height_; ++y)
  576. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  577. data_ = newData;
  578. }
  579. else
  580. {
  581. if (compressedFormat_ > CF_DXT5)
  582. {
  583. LOGERROR("FlipVertical not yet implemented for other compressed formats than DXT1,3,5");
  584. return;
  585. }
  586. // Memory use = combined size of the compressed mip levels
  587. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  588. unsigned dataOffset = 0;
  589. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  590. {
  591. CompressedLevel level = GetCompressedLevel(i);
  592. if (!level.data_)
  593. {
  594. LOGERROR("Got compressed level with no data, aborting vertical flip");
  595. return;
  596. }
  597. for (unsigned y = 0; y < level.rows_; ++y)
  598. {
  599. unsigned char* src = level.data_ + y * level.rowSize_;
  600. unsigned char* dest = newData.Get() + dataOffset + (level.rows_ - y - 1) * level.rowSize_;
  601. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  602. FlipBlockVertical(dest + x, src + x, compressedFormat_);
  603. }
  604. dataOffset += level.dataSize_;
  605. }
  606. data_ = newData;
  607. }
  608. }
  609. bool Image::Resize(int width, int height)
  610. {
  611. PROFILE(ResizeImage);
  612. if (IsCompressed())
  613. {
  614. LOGERROR("Resize not supported for compressed images");
  615. return false;
  616. }
  617. if (depth_ > 1)
  618. {
  619. LOGERROR("Resize not supported for 3D images");
  620. return false;
  621. }
  622. if (!data_ || width <= 0 || height <= 0)
  623. return false;
  624. /// \todo Reducing image size does not sample all needed pixels
  625. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  626. for (int y = 0; y < height; ++y)
  627. {
  628. for (int x = 0; x < width; ++x)
  629. {
  630. // Calculate float coordinates between 0 - 1 for resampling
  631. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  632. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  633. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  634. unsigned char* dest = newData + (y * width + x) * components_;
  635. unsigned char* src = (unsigned char*)&uintColor;
  636. switch (components_)
  637. {
  638. case 4:
  639. dest[3] = src[3];
  640. // Fall through
  641. case 3:
  642. dest[2] = src[2];
  643. // Fall through
  644. case 2:
  645. dest[1] = src[1];
  646. // Fall through
  647. default:
  648. dest[0] = src[0];
  649. break;
  650. }
  651. }
  652. }
  653. width_ = width;
  654. height_ = height;
  655. data_ = newData;
  656. SetMemoryUse(width * height * depth_ * components_);
  657. return true;
  658. }
  659. void Image::Clear(const Color& color)
  660. {
  661. ClearInt(color.ToUInt());
  662. }
  663. void Image::ClearInt(unsigned uintColor)
  664. {
  665. PROFILE(ClearImage);
  666. if (!data_)
  667. return;
  668. if (IsCompressed())
  669. {
  670. LOGERROR("Clear not supported for compressed images");
  671. return;
  672. }
  673. unsigned char* src = (unsigned char*)&uintColor;
  674. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  675. data_[i] = src[i % components_];
  676. }
  677. bool Image::SaveBMP(const String& fileName) const
  678. {
  679. PROFILE(SaveImageBMP);
  680. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  681. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  682. {
  683. LOGERROR("Access denied to " + fileName);
  684. return false;
  685. }
  686. if (IsCompressed())
  687. {
  688. LOGERROR("Can not save compressed image to BMP");
  689. return false;
  690. }
  691. if (data_)
  692. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  693. else
  694. return false;
  695. }
  696. bool Image::SavePNG(const String& fileName) const
  697. {
  698. PROFILE(SaveImagePNG);
  699. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  700. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  701. {
  702. LOGERROR("Access denied to " + fileName);
  703. return false;
  704. }
  705. if (IsCompressed())
  706. {
  707. LOGERROR("Can not save compressed image to PNG");
  708. return false;
  709. }
  710. if (data_)
  711. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  712. else
  713. return false;
  714. }
  715. bool Image::SaveTGA(const String& fileName) const
  716. {
  717. PROFILE(SaveImageTGA);
  718. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  719. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  720. {
  721. LOGERROR("Access denied to " + fileName);
  722. return false;
  723. }
  724. if (IsCompressed())
  725. {
  726. LOGERROR("Can not save compressed image to TGA");
  727. return false;
  728. }
  729. if (data_)
  730. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  731. else
  732. return false;
  733. }
  734. bool Image::SaveJPG(const String & fileName, int quality) const
  735. {
  736. PROFILE(SaveImageJPG);
  737. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  738. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  739. {
  740. LOGERROR("Access denied to " + fileName);
  741. return false;
  742. }
  743. if (IsCompressed())
  744. {
  745. LOGERROR("Can not save compressed image to JPG");
  746. return false;
  747. }
  748. if (data_)
  749. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  750. else
  751. return false;
  752. }
  753. Color Image::GetPixel(int x, int y) const
  754. {
  755. return GetPixel(x, y, 0);
  756. }
  757. Color Image::GetPixel(int x, int y, int z) const
  758. {
  759. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  760. return Color::BLACK;
  761. x = Clamp(x, 0, width_ - 1);
  762. y = Clamp(y, 0, height_ - 1);
  763. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  764. Color ret;
  765. switch (components_)
  766. {
  767. case 4:
  768. ret.a_ = (float)src[3] / 255.0f;
  769. // Fall through
  770. case 3:
  771. ret.b_ = (float)src[2] / 255.0f;
  772. // Fall through
  773. case 2:
  774. ret.g_ = (float)src[1] / 255.0f;
  775. ret.r_ = (float)src[0] / 255.0f;
  776. break;
  777. default:
  778. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  779. break;
  780. }
  781. return ret;
  782. }
  783. unsigned Image::GetPixelInt(int x, int y) const
  784. {
  785. return GetPixelInt(x, y, 0);
  786. }
  787. unsigned Image::GetPixelInt(int x, int y, int z) const
  788. {
  789. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  790. return 0xff000000;
  791. x = Clamp(x, 0, width_ - 1);
  792. y = Clamp(y, 0, height_ - 1);
  793. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  794. unsigned ret = 0;
  795. if (components_ < 4)
  796. ret |= 0xff000000;
  797. switch (components_)
  798. {
  799. case 4:
  800. ret |= (unsigned)src[3] << 24;
  801. // Fall through
  802. case 3:
  803. ret |= (unsigned)src[2] << 16;
  804. // Fall through
  805. case 2:
  806. ret |= (unsigned)src[1] << 8;
  807. ret |= (unsigned)src[0];
  808. break;
  809. default:
  810. ret |= (unsigned)src[0] << 16;
  811. ret |= (unsigned)src[0] << 8;
  812. ret |= (unsigned)src[0];
  813. break;
  814. }
  815. return ret;
  816. }
  817. Color Image::GetPixelBilinear(float x, float y) const
  818. {
  819. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  820. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  821. int xI = (int)x;
  822. int yI = (int)y;
  823. float xF = x - floorf(x);
  824. float yF = y - floorf(y);
  825. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  826. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  827. return topColor.Lerp(bottomColor, yF);
  828. }
  829. Color Image::GetPixelTrilinear(float x, float y, float z) const
  830. {
  831. if (depth_ < 2)
  832. return GetPixelBilinear(x, y);
  833. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  834. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  835. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  836. int xI = (int)x;
  837. int yI = (int)y;
  838. int zI = (int)z;
  839. if (zI == depth_ - 1)
  840. return GetPixelBilinear(x, y);
  841. float xF = x - floorf(x);
  842. float yF = y - floorf(y);
  843. float zF = z - floorf(z);
  844. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  845. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  846. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  847. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  848. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  849. Color colorFar = topColorNear.Lerp(bottomColorNear, yF);
  850. return colorNear.Lerp(colorFar, zF);
  851. }
  852. SharedPtr<Image> Image::GetNextLevel() const
  853. {
  854. if (IsCompressed())
  855. {
  856. LOGERROR("Can not generate mip level from compressed data");
  857. return SharedPtr<Image>();
  858. }
  859. if (components_ < 1 || components_ > 4)
  860. {
  861. LOGERROR("Illegal number of image components for mip level generation");
  862. return SharedPtr<Image>();
  863. }
  864. if (nextLevel_)
  865. return nextLevel_;
  866. PROFILE(CalculateImageMipLevel);
  867. int widthOut = width_ / 2;
  868. int heightOut = height_ / 2;
  869. int depthOut = depth_ / 2;
  870. if (widthOut < 1)
  871. widthOut = 1;
  872. if (heightOut < 1)
  873. heightOut = 1;
  874. if (depthOut < 1)
  875. depthOut = 1;
  876. SharedPtr<Image> mipImage(new Image(context_));
  877. if (depth_ > 1)
  878. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  879. else
  880. mipImage->SetSize(widthOut, heightOut, components_);
  881. const unsigned char* pixelDataIn = data_.Get();
  882. unsigned char* pixelDataOut = mipImage->data_.Get();
  883. // 1D case
  884. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  885. {
  886. // Loop using the larger dimension
  887. if (widthOut < heightOut)
  888. widthOut = heightOut;
  889. switch (components_)
  890. {
  891. case 1:
  892. for (int x = 0; x < widthOut; ++x)
  893. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
  894. break;
  895. case 2:
  896. for (int x = 0; x < widthOut*2; x += 2)
  897. {
  898. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
  899. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
  900. }
  901. break;
  902. case 3:
  903. for (int x = 0; x < widthOut*3; x += 3)
  904. {
  905. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
  906. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
  907. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
  908. }
  909. break;
  910. case 4:
  911. for (int x = 0; x < widthOut*4; x += 4)
  912. {
  913. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
  914. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
  915. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
  916. pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
  917. }
  918. break;
  919. }
  920. }
  921. // 2D case
  922. else if (depth_ == 1)
  923. {
  924. switch (components_)
  925. {
  926. case 1:
  927. for (int y = 0; y < heightOut; ++y)
  928. {
  929. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
  930. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
  931. unsigned char* out = &pixelDataOut[y*widthOut];
  932. for (int x = 0; x < widthOut; ++x)
  933. {
  934. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
  935. }
  936. }
  937. break;
  938. case 2:
  939. for (int y = 0; y < heightOut; ++y)
  940. {
  941. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
  942. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
  943. unsigned char* out = &pixelDataOut[y*widthOut*2];
  944. for (int x = 0; x < widthOut*2; x += 2)
  945. {
  946. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
  947. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
  948. }
  949. }
  950. break;
  951. case 3:
  952. for (int y = 0; y < heightOut; ++y)
  953. {
  954. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
  955. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
  956. unsigned char* out = &pixelDataOut[y*widthOut*3];
  957. for (int x = 0; x < widthOut*3; x += 3)
  958. {
  959. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
  960. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
  961. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
  962. }
  963. }
  964. break;
  965. case 4:
  966. for (int y = 0; y < heightOut; ++y)
  967. {
  968. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
  969. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
  970. unsigned char* out = &pixelDataOut[y*widthOut*4];
  971. for (int x = 0; x < widthOut*4; x += 4)
  972. {
  973. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
  974. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
  975. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
  976. out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
  977. }
  978. }
  979. break;
  980. }
  981. }
  982. // 3D case
  983. else
  984. {
  985. switch (components_)
  986. {
  987. case 1:
  988. for (int z = 0; z < depthOut; ++z)
  989. {
  990. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_];
  991. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_];
  992. for (int y = 0; y < heightOut; ++y)
  993. {
  994. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_];
  995. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_];
  996. const unsigned char* inInnerUpper = &inInner[(y*2)*width_];
  997. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_];
  998. unsigned char* out = &pixelDataOut[z*widthOut*heightOut + y*widthOut];
  999. for (int x = 0; x < widthOut; ++x)
  1000. {
  1001. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+1] + inOuterLower[x*2] + inOuterLower[x*2+1] +
  1002. inInnerUpper[x*2] + inInnerUpper[x*2+1] + inInnerLower[x*2] + inInnerLower[x*2+1]) >> 3;
  1003. }
  1004. }
  1005. }
  1006. break;
  1007. case 2:
  1008. for (int z = 0; z < depthOut; ++z)
  1009. {
  1010. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*2];
  1011. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*2];
  1012. for (int y = 0; y < heightOut; ++y)
  1013. {
  1014. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*2];
  1015. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*2];
  1016. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*2];
  1017. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*2];
  1018. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*2 + y*widthOut*2];
  1019. for (int x = 0; x < widthOut*2; x += 2)
  1020. {
  1021. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+2] + inOuterLower[x*2] + inOuterLower[x*2+2] +
  1022. inInnerUpper[x*2] + inInnerUpper[x*2+2] + inInnerLower[x*2] + inInnerLower[x*2+2]) >> 3;
  1023. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+3] + inOuterLower[x*2+1] + inOuterLower[x*2+3] +
  1024. inInnerUpper[x*2+1] + inInnerUpper[x*2+3] + inInnerLower[x*2+1] + inInnerLower[x*2+3]) >> 3;
  1025. }
  1026. }
  1027. }
  1028. break;
  1029. case 3:
  1030. for (int z = 0; z < depthOut; ++z)
  1031. {
  1032. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*3];
  1033. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*3];
  1034. for (int y = 0; y < heightOut; ++y)
  1035. {
  1036. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*3];
  1037. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*3];
  1038. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*3];
  1039. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*3];
  1040. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*3 + y*widthOut*3];
  1041. for (int x = 0; x < widthOut*3; x += 3)
  1042. {
  1043. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+3] + inOuterLower[x*2] + inOuterLower[x*2+3] +
  1044. inInnerUpper[x*2] + inInnerUpper[x*2+3] + inInnerLower[x*2] + inInnerLower[x*2+3]) >> 3;
  1045. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+4] + inOuterLower[x*2+1] + inOuterLower[x*2+4] +
  1046. inInnerUpper[x*2+1] + inInnerUpper[x*2+4] + inInnerLower[x*2+1] + inInnerLower[x*2+4]) >> 3;
  1047. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+5] + inOuterLower[x*2+2] + inOuterLower[x*2+5] +
  1048. inInnerUpper[x*2+2] + inInnerUpper[x*2+5] + inInnerLower[x*2+2] + inInnerLower[x*2+5]) >> 3;
  1049. }
  1050. }
  1051. }
  1052. break;
  1053. case 4:
  1054. for (int z = 0; z < depthOut; ++z)
  1055. {
  1056. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*4];
  1057. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*4];
  1058. for (int y = 0; y < heightOut; ++y)
  1059. {
  1060. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*4];
  1061. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*4];
  1062. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*4];
  1063. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*4];
  1064. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*4 + y*widthOut*4];
  1065. for (int x = 0; x < widthOut*4; x += 4)
  1066. {
  1067. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+4] + inOuterLower[x*2] + inOuterLower[x*2+4] +
  1068. inInnerUpper[x*2] + inInnerUpper[x*2+4] + inInnerLower[x*2] + inInnerLower[x*2+4]) >> 3;
  1069. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+5] + inOuterLower[x*2+1] + inOuterLower[x*2+5] +
  1070. inInnerUpper[x*2+1] + inInnerUpper[x*2+5] + inInnerLower[x*2+1] + inInnerLower[x*2+5]) >> 3;
  1071. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+6] + inOuterLower[x*2+2] + inOuterLower[x*2+6] +
  1072. inInnerUpper[x*2+2] + inInnerUpper[x*2+6] + inInnerLower[x*2+2] + inInnerLower[x*2+6]) >> 3;
  1073. }
  1074. }
  1075. }
  1076. break;
  1077. }
  1078. }
  1079. return mipImage;
  1080. }
  1081. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1082. {
  1083. CompressedLevel level;
  1084. if (compressedFormat_ == CF_NONE)
  1085. {
  1086. LOGERROR("Image is not compressed");
  1087. return level;
  1088. }
  1089. if (index >= numCompressedLevels_)
  1090. {
  1091. LOGERROR("Compressed image mip level out of bounds");
  1092. return level;
  1093. }
  1094. level.format_ = compressedFormat_;
  1095. level.width_ = width_;
  1096. level.height_ = height_;
  1097. level.depth_ = depth_;
  1098. if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1099. {
  1100. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1101. unsigned i = 0;
  1102. unsigned offset = 0;
  1103. for (;;)
  1104. {
  1105. if (!level.width_)
  1106. level.width_ = 1;
  1107. if (!level.height_)
  1108. level.height_ = 1;
  1109. if (!level.depth_)
  1110. level.depth_ = 1;
  1111. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1112. level.rows_ = ((level.height_ + 3) / 4);
  1113. level.data_ = data_.Get() + offset;
  1114. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1115. if (offset + level.dataSize_ > GetMemoryUse())
  1116. {
  1117. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1118. " Datasize: " + String(GetMemoryUse()));
  1119. level.data_ = 0;
  1120. return level;
  1121. }
  1122. if (i == index)
  1123. return level;
  1124. offset += level.dataSize_;
  1125. level.width_ /= 2;
  1126. level.height_ /= 2;
  1127. level.depth_ /= 2;
  1128. ++i;
  1129. }
  1130. }
  1131. else
  1132. {
  1133. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1134. unsigned i = 0;
  1135. unsigned offset = 0;
  1136. for (;;)
  1137. {
  1138. if (!level.width_)
  1139. level.width_ = 1;
  1140. if (!level.height_)
  1141. level.height_ = 1;
  1142. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1143. int dataHeight = Max(level.height_, 8);
  1144. level.data_ = data_.Get() + offset;
  1145. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1146. level.rows_ = dataHeight;
  1147. level.rowSize_ = level.dataSize_ / level.rows_;
  1148. if (offset + level.dataSize_ > GetMemoryUse())
  1149. {
  1150. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1151. " Datasize: " + String(GetMemoryUse()));
  1152. level.data_ = 0;
  1153. return level;
  1154. }
  1155. if (i == index)
  1156. return level;
  1157. offset += level.dataSize_;
  1158. level.width_ /= 2;
  1159. level.height_ /= 2;
  1160. ++i;
  1161. }
  1162. }
  1163. }
  1164. Image* Image::GetSubimage(const IntRect& rect) const
  1165. {
  1166. if (!data_)
  1167. return 0;
  1168. if (depth_ > 1)
  1169. {
  1170. LOGERROR("Subimage not supported for 3D images");
  1171. return 0;
  1172. }
  1173. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1174. {
  1175. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1176. return 0;
  1177. }
  1178. if (!IsCompressed())
  1179. {
  1180. int x = rect.left_;
  1181. int y = rect.top_;
  1182. int width = rect.Width();
  1183. int height = rect.Height();
  1184. Image* image = new Image(context_);
  1185. image->SetSize(width, height, components_);
  1186. unsigned char* dest = image->GetData();
  1187. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1188. for (int i = 0; i < height; ++i)
  1189. {
  1190. memcpy(dest, src, width * components_);
  1191. dest += width * components_;
  1192. src += width_ * components_;
  1193. }
  1194. return image;
  1195. }
  1196. else
  1197. {
  1198. // Pad the region to be a multiple of block size
  1199. IntRect paddedRect = rect;
  1200. paddedRect.left_ = (rect.left_ / 4) * 4;
  1201. paddedRect.top_ = (rect.top_ / 4) * 4;
  1202. paddedRect.right_ = (rect.right_ / 4) * 4;
  1203. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1204. IntRect currentRect = paddedRect;
  1205. PODVector<unsigned char> subimageData;
  1206. unsigned subimageLevels = 0;
  1207. // Save as many mips as possible until the next mip would cross a block boundary
  1208. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1209. {
  1210. CompressedLevel level = GetCompressedLevel(i);
  1211. if (!level.data_)
  1212. break;
  1213. // Mips are stored continuously
  1214. unsigned destStartOffset = subimageData.Size();
  1215. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1216. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1217. if (!destSize)
  1218. break;
  1219. subimageData.Resize(destStartOffset + destSize);
  1220. unsigned char* dest = &subimageData[destStartOffset];
  1221. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1222. {
  1223. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1224. memcpy(dest, src, destRowSize);
  1225. dest += destRowSize;
  1226. }
  1227. ++subimageLevels;
  1228. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1229. break;
  1230. else
  1231. {
  1232. currentRect.left_ /= 2;
  1233. currentRect.right_ /= 2;
  1234. currentRect.top_ /= 2;
  1235. currentRect.bottom_ /= 2;
  1236. }
  1237. }
  1238. if (!subimageLevels)
  1239. {
  1240. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1241. return 0;
  1242. }
  1243. Image* image = new Image(context_);
  1244. image->width_ = paddedRect.Width();
  1245. image->height_ = paddedRect.Height();
  1246. image->depth_ = 1;
  1247. image->compressedFormat_ = compressedFormat_;
  1248. image->numCompressedLevels_ = subimageLevels;
  1249. image->components_ = components_;
  1250. image->data_ = new unsigned char[subimageData.Size()];
  1251. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1252. image->SetMemoryUse(subimageData.Size());
  1253. return image;
  1254. }
  1255. }
  1256. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1257. {
  1258. if (!data_)
  1259. return 0;
  1260. if (depth_ > 1)
  1261. {
  1262. LOGERROR("Can not get SDL surface from 3D image");
  1263. return 0;
  1264. }
  1265. if (IsCompressed())
  1266. {
  1267. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1268. return 0;
  1269. }
  1270. if (components_ < 3)
  1271. {
  1272. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1273. return 0;
  1274. }
  1275. IntRect imageRect = rect;
  1276. // Use full image if illegal rect
  1277. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1278. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1279. {
  1280. imageRect.left_ = 0;
  1281. imageRect.top_ = 0;
  1282. imageRect.right_ = width_;
  1283. imageRect.bottom_ = height_;
  1284. }
  1285. int imageWidth = width_;
  1286. int width = imageRect.Width();
  1287. int height = imageRect.Height();
  1288. // Assume little-endian for all the supported platforms
  1289. unsigned rMask = 0x000000ff;
  1290. unsigned gMask = 0x0000ff00;
  1291. unsigned bMask = 0x00ff0000;
  1292. unsigned aMask = 0xff000000;
  1293. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1294. if (surface)
  1295. {
  1296. SDL_LockSurface(surface);
  1297. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1298. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1299. for (int i = 0; i < height; ++i)
  1300. {
  1301. memcpy(destination, source, components_ * width);
  1302. destination += surface->pitch;
  1303. source += components_ * imageWidth;
  1304. }
  1305. SDL_UnlockSurface(surface);
  1306. }
  1307. else
  1308. LOGERROR("Failed to create SDL surface from image " + GetName());
  1309. return surface;
  1310. }
  1311. void Image::PrecalculateLevels()
  1312. {
  1313. if (!data_ || IsCompressed())
  1314. return;
  1315. PROFILE(PrecalculateImageMipLevels);
  1316. nextLevel_.Reset();
  1317. if (width_ > 1 || height_ > 1)
  1318. {
  1319. SharedPtr<Image> current = GetNextLevel();
  1320. nextLevel_ = current;
  1321. while (current && (current->width_ > 1 || current->height_ > 1))
  1322. {
  1323. current->nextLevel_ = current->GetNextLevel();
  1324. current = current->nextLevel_;
  1325. }
  1326. }
  1327. }
  1328. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1329. {
  1330. unsigned dataSize = source.GetSize();
  1331. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1332. source.Read(buffer.Get(), dataSize);
  1333. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int *)&components, 0);
  1334. }
  1335. void Image::FreeImageData(unsigned char* pixelData)
  1336. {
  1337. if (!pixelData)
  1338. return;
  1339. stbi_image_free(pixelData);
  1340. }
  1341. }