Image.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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. bool Image::FlipHorizontal()
  563. {
  564. if (!data_)
  565. return false;
  566. if (depth_ > 1)
  567. {
  568. LOGERROR("FlipHorizontal not supported for 3D images");
  569. return false;
  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. {
  577. for (int x = 0; x < width_; ++x)
  578. {
  579. for (unsigned c = 0; c < components_; ++c)
  580. newData[y * rowSize + x * components_ + c] = data_[y * rowSize + (width_ - x - 1) * components_ + c];
  581. }
  582. }
  583. data_ = newData;
  584. }
  585. else
  586. {
  587. if (compressedFormat_ > CF_DXT5)
  588. {
  589. LOGERROR("FlipHorizontal not yet implemented for other compressed formats than DXT1,3,5");
  590. return false;
  591. }
  592. // Memory use = combined size of the compressed mip levels
  593. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  594. unsigned dataOffset = 0;
  595. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  596. {
  597. CompressedLevel level = GetCompressedLevel(i);
  598. if (!level.data_)
  599. {
  600. LOGERROR("Got compressed level with no data, aborting horizontal flip");
  601. return false;
  602. }
  603. for (unsigned y = 0; y < level.rows_; ++y)
  604. {
  605. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  606. {
  607. unsigned char* src = level.data_ + y * level.rowSize_ + (level.rowSize_ - level.blockSize_ - x);
  608. unsigned char* dest = newData.Get() + y * level.rowSize_ + x;
  609. FlipBlockHorizontal(dest, src, compressedFormat_);
  610. }
  611. }
  612. dataOffset += level.dataSize_;
  613. }
  614. data_ = newData;
  615. }
  616. return true;
  617. }
  618. bool Image::FlipVertical()
  619. {
  620. if (!data_)
  621. return false;
  622. if (depth_ > 1)
  623. {
  624. LOGERROR("FlipVertical not supported for 3D images");
  625. return false;
  626. }
  627. if (!IsCompressed())
  628. {
  629. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  630. unsigned rowSize = width_ * components_;
  631. for (int y = 0; y < height_; ++y)
  632. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  633. data_ = newData;
  634. }
  635. else
  636. {
  637. if (compressedFormat_ > CF_DXT5)
  638. {
  639. LOGERROR("FlipVertical not yet implemented for other compressed formats than DXT1,3,5");
  640. return false;
  641. }
  642. // Memory use = combined size of the compressed mip levels
  643. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  644. unsigned dataOffset = 0;
  645. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  646. {
  647. CompressedLevel level = GetCompressedLevel(i);
  648. if (!level.data_)
  649. {
  650. LOGERROR("Got compressed level with no data, aborting vertical flip");
  651. return false;
  652. }
  653. for (unsigned y = 0; y < level.rows_; ++y)
  654. {
  655. unsigned char* src = level.data_ + y * level.rowSize_;
  656. unsigned char* dest = newData.Get() + dataOffset + (level.rows_ - y - 1) * level.rowSize_;
  657. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  658. FlipBlockVertical(dest + x, src + x, compressedFormat_);
  659. }
  660. dataOffset += level.dataSize_;
  661. }
  662. data_ = newData;
  663. }
  664. return true;
  665. }
  666. bool Image::Resize(int width, int height)
  667. {
  668. PROFILE(ResizeImage);
  669. if (IsCompressed())
  670. {
  671. LOGERROR("Resize not supported for compressed images");
  672. return false;
  673. }
  674. if (depth_ > 1)
  675. {
  676. LOGERROR("Resize not supported for 3D images");
  677. return false;
  678. }
  679. if (!data_ || width <= 0 || height <= 0)
  680. return false;
  681. /// \todo Reducing image size does not sample all needed pixels
  682. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  683. for (int y = 0; y < height; ++y)
  684. {
  685. for (int x = 0; x < width; ++x)
  686. {
  687. // Calculate float coordinates between 0 - 1 for resampling
  688. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  689. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  690. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  691. unsigned char* dest = newData + (y * width + x) * components_;
  692. unsigned char* src = (unsigned char*)&uintColor;
  693. switch (components_)
  694. {
  695. case 4:
  696. dest[3] = src[3];
  697. // Fall through
  698. case 3:
  699. dest[2] = src[2];
  700. // Fall through
  701. case 2:
  702. dest[1] = src[1];
  703. // Fall through
  704. default:
  705. dest[0] = src[0];
  706. break;
  707. }
  708. }
  709. }
  710. width_ = width;
  711. height_ = height;
  712. data_ = newData;
  713. SetMemoryUse(width * height * depth_ * components_);
  714. return true;
  715. }
  716. void Image::Clear(const Color& color)
  717. {
  718. ClearInt(color.ToUInt());
  719. }
  720. void Image::ClearInt(unsigned uintColor)
  721. {
  722. PROFILE(ClearImage);
  723. if (!data_)
  724. return;
  725. if (IsCompressed())
  726. {
  727. LOGERROR("Clear not supported for compressed images");
  728. return;
  729. }
  730. unsigned char* src = (unsigned char*)&uintColor;
  731. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  732. data_[i] = src[i % components_];
  733. }
  734. bool Image::SaveBMP(const String& fileName) const
  735. {
  736. PROFILE(SaveImageBMP);
  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 BMP");
  746. return false;
  747. }
  748. if (data_)
  749. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  750. else
  751. return false;
  752. }
  753. bool Image::SavePNG(const String& fileName) const
  754. {
  755. PROFILE(SaveImagePNG);
  756. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  757. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  758. {
  759. LOGERROR("Access denied to " + fileName);
  760. return false;
  761. }
  762. if (IsCompressed())
  763. {
  764. LOGERROR("Can not save compressed image to PNG");
  765. return false;
  766. }
  767. if (data_)
  768. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  769. else
  770. return false;
  771. }
  772. bool Image::SaveTGA(const String& fileName) const
  773. {
  774. PROFILE(SaveImageTGA);
  775. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  776. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  777. {
  778. LOGERROR("Access denied to " + fileName);
  779. return false;
  780. }
  781. if (IsCompressed())
  782. {
  783. LOGERROR("Can not save compressed image to TGA");
  784. return false;
  785. }
  786. if (data_)
  787. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  788. else
  789. return false;
  790. }
  791. bool Image::SaveJPG(const String & fileName, int quality) const
  792. {
  793. PROFILE(SaveImageJPG);
  794. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  795. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  796. {
  797. LOGERROR("Access denied to " + fileName);
  798. return false;
  799. }
  800. if (IsCompressed())
  801. {
  802. LOGERROR("Can not save compressed image to JPG");
  803. return false;
  804. }
  805. if (data_)
  806. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  807. else
  808. return false;
  809. }
  810. Color Image::GetPixel(int x, int y) const
  811. {
  812. return GetPixel(x, y, 0);
  813. }
  814. Color Image::GetPixel(int x, int y, int z) const
  815. {
  816. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  817. return Color::BLACK;
  818. x = Clamp(x, 0, width_ - 1);
  819. y = Clamp(y, 0, height_ - 1);
  820. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  821. Color ret;
  822. switch (components_)
  823. {
  824. case 4:
  825. ret.a_ = (float)src[3] / 255.0f;
  826. // Fall through
  827. case 3:
  828. ret.b_ = (float)src[2] / 255.0f;
  829. // Fall through
  830. case 2:
  831. ret.g_ = (float)src[1] / 255.0f;
  832. ret.r_ = (float)src[0] / 255.0f;
  833. break;
  834. default:
  835. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  836. break;
  837. }
  838. return ret;
  839. }
  840. unsigned Image::GetPixelInt(int x, int y) const
  841. {
  842. return GetPixelInt(x, y, 0);
  843. }
  844. unsigned Image::GetPixelInt(int x, int y, int z) const
  845. {
  846. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  847. return 0xff000000;
  848. x = Clamp(x, 0, width_ - 1);
  849. y = Clamp(y, 0, height_ - 1);
  850. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  851. unsigned ret = 0;
  852. if (components_ < 4)
  853. ret |= 0xff000000;
  854. switch (components_)
  855. {
  856. case 4:
  857. ret |= (unsigned)src[3] << 24;
  858. // Fall through
  859. case 3:
  860. ret |= (unsigned)src[2] << 16;
  861. // Fall through
  862. case 2:
  863. ret |= (unsigned)src[1] << 8;
  864. ret |= (unsigned)src[0];
  865. break;
  866. default:
  867. ret |= (unsigned)src[0] << 16;
  868. ret |= (unsigned)src[0] << 8;
  869. ret |= (unsigned)src[0];
  870. break;
  871. }
  872. return ret;
  873. }
  874. Color Image::GetPixelBilinear(float x, float y) const
  875. {
  876. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  877. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  878. int xI = (int)x;
  879. int yI = (int)y;
  880. float xF = x - floorf(x);
  881. float yF = y - floorf(y);
  882. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  883. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  884. return topColor.Lerp(bottomColor, yF);
  885. }
  886. Color Image::GetPixelTrilinear(float x, float y, float z) const
  887. {
  888. if (depth_ < 2)
  889. return GetPixelBilinear(x, y);
  890. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  891. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  892. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  893. int xI = (int)x;
  894. int yI = (int)y;
  895. int zI = (int)z;
  896. if (zI == depth_ - 1)
  897. return GetPixelBilinear(x, y);
  898. float xF = x - floorf(x);
  899. float yF = y - floorf(y);
  900. float zF = z - floorf(z);
  901. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  902. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  903. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  904. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  905. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  906. Color colorFar = topColorFar.Lerp(bottomColorFar, yF);
  907. return colorNear.Lerp(colorFar, zF);
  908. }
  909. SharedPtr<Image> Image::GetNextLevel() const
  910. {
  911. if (IsCompressed())
  912. {
  913. LOGERROR("Can not generate mip level from compressed data");
  914. return SharedPtr<Image>();
  915. }
  916. if (components_ < 1 || components_ > 4)
  917. {
  918. LOGERROR("Illegal number of image components for mip level generation");
  919. return SharedPtr<Image>();
  920. }
  921. if (nextLevel_)
  922. return nextLevel_;
  923. PROFILE(CalculateImageMipLevel);
  924. int widthOut = width_ / 2;
  925. int heightOut = height_ / 2;
  926. int depthOut = depth_ / 2;
  927. if (widthOut < 1)
  928. widthOut = 1;
  929. if (heightOut < 1)
  930. heightOut = 1;
  931. if (depthOut < 1)
  932. depthOut = 1;
  933. SharedPtr<Image> mipImage(new Image(context_));
  934. if (depth_ > 1)
  935. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  936. else
  937. mipImage->SetSize(widthOut, heightOut, components_);
  938. const unsigned char* pixelDataIn = data_.Get();
  939. unsigned char* pixelDataOut = mipImage->data_.Get();
  940. // 1D case
  941. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  942. {
  943. // Loop using the larger dimension
  944. if (widthOut < heightOut)
  945. widthOut = heightOut;
  946. switch (components_)
  947. {
  948. case 1:
  949. for (int x = 0; x < widthOut; ++x)
  950. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+1]) >> 1;
  951. break;
  952. case 2:
  953. for (int x = 0; x < widthOut*2; x += 2)
  954. {
  955. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+2]) >> 1;
  956. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+3]) >> 1;
  957. }
  958. break;
  959. case 3:
  960. for (int x = 0; x < widthOut*3; x += 3)
  961. {
  962. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+3]) >> 1;
  963. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+4]) >> 1;
  964. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+5]) >> 1;
  965. }
  966. break;
  967. case 4:
  968. for (int x = 0; x < widthOut*4; x += 4)
  969. {
  970. pixelDataOut[x] = ((unsigned)pixelDataIn[x*2] + pixelDataIn[x*2+4]) >> 1;
  971. pixelDataOut[x+1] = ((unsigned)pixelDataIn[x*2+1] + pixelDataIn[x*2+5]) >> 1;
  972. pixelDataOut[x+2] = ((unsigned)pixelDataIn[x*2+2] + pixelDataIn[x*2+6]) >> 1;
  973. pixelDataOut[x+3] = ((unsigned)pixelDataIn[x*2+3] + pixelDataIn[x*2+7]) >> 1;
  974. }
  975. break;
  976. }
  977. }
  978. // 2D case
  979. else if (depth_ == 1)
  980. {
  981. switch (components_)
  982. {
  983. case 1:
  984. for (int y = 0; y < heightOut; ++y)
  985. {
  986. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_];
  987. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_];
  988. unsigned char* out = &pixelDataOut[y*widthOut];
  989. for (int x = 0; x < widthOut; ++x)
  990. {
  991. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+1] + inLower[x*2] + inLower[x*2+1]) >> 2;
  992. }
  993. }
  994. break;
  995. case 2:
  996. for (int y = 0; y < heightOut; ++y)
  997. {
  998. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*2];
  999. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*2];
  1000. unsigned char* out = &pixelDataOut[y*widthOut*2];
  1001. for (int x = 0; x < widthOut*2; x += 2)
  1002. {
  1003. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+2] + inLower[x*2] + inLower[x*2+2]) >> 2;
  1004. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+3] + inLower[x*2+1] + inLower[x*2+3]) >> 2;
  1005. }
  1006. }
  1007. break;
  1008. case 3:
  1009. for (int y = 0; y < heightOut; ++y)
  1010. {
  1011. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*3];
  1012. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*3];
  1013. unsigned char* out = &pixelDataOut[y*widthOut*3];
  1014. for (int x = 0; x < widthOut*3; x += 3)
  1015. {
  1016. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+3] + inLower[x*2] + inLower[x*2+3]) >> 2;
  1017. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+4] + inLower[x*2+1] + inLower[x*2+4]) >> 2;
  1018. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+5] + inLower[x*2+2] + inLower[x*2+5]) >> 2;
  1019. }
  1020. }
  1021. break;
  1022. case 4:
  1023. for (int y = 0; y < heightOut; ++y)
  1024. {
  1025. const unsigned char* inUpper = &pixelDataIn[(y*2)*width_*4];
  1026. const unsigned char* inLower = &pixelDataIn[(y*2+1)*width_*4];
  1027. unsigned char* out = &pixelDataOut[y*widthOut*4];
  1028. for (int x = 0; x < widthOut*4; x += 4)
  1029. {
  1030. out[x] = ((unsigned)inUpper[x*2] + inUpper[x*2+4] + inLower[x*2] + inLower[x*2+4]) >> 2;
  1031. out[x+1] = ((unsigned)inUpper[x*2+1] + inUpper[x*2+5] + inLower[x*2+1] + inLower[x*2+5]) >> 2;
  1032. out[x+2] = ((unsigned)inUpper[x*2+2] + inUpper[x*2+6] + inLower[x*2+2] + inLower[x*2+6]) >> 2;
  1033. out[x+3] = ((unsigned)inUpper[x*2+3] + inUpper[x*2+7] + inLower[x*2+3] + inLower[x*2+7]) >> 2;
  1034. }
  1035. }
  1036. break;
  1037. }
  1038. }
  1039. // 3D case
  1040. else
  1041. {
  1042. switch (components_)
  1043. {
  1044. case 1:
  1045. for (int z = 0; z < depthOut; ++z)
  1046. {
  1047. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_];
  1048. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_];
  1049. for (int y = 0; y < heightOut; ++y)
  1050. {
  1051. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_];
  1052. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_];
  1053. const unsigned char* inInnerUpper = &inInner[(y*2)*width_];
  1054. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_];
  1055. unsigned char* out = &pixelDataOut[z*widthOut*heightOut + y*widthOut];
  1056. for (int x = 0; x < widthOut; ++x)
  1057. {
  1058. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+1] + inOuterLower[x*2] + inOuterLower[x*2+1] +
  1059. inInnerUpper[x*2] + inInnerUpper[x*2+1] + inInnerLower[x*2] + inInnerLower[x*2+1]) >> 3;
  1060. }
  1061. }
  1062. }
  1063. break;
  1064. case 2:
  1065. for (int z = 0; z < depthOut; ++z)
  1066. {
  1067. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*2];
  1068. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*2];
  1069. for (int y = 0; y < heightOut; ++y)
  1070. {
  1071. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*2];
  1072. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*2];
  1073. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*2];
  1074. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*2];
  1075. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*2 + y*widthOut*2];
  1076. for (int x = 0; x < widthOut*2; x += 2)
  1077. {
  1078. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+2] + inOuterLower[x*2] + inOuterLower[x*2+2] +
  1079. inInnerUpper[x*2] + inInnerUpper[x*2+2] + inInnerLower[x*2] + inInnerLower[x*2+2]) >> 3;
  1080. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+3] + inOuterLower[x*2+1] + inOuterLower[x*2+3] +
  1081. inInnerUpper[x*2+1] + inInnerUpper[x*2+3] + inInnerLower[x*2+1] + inInnerLower[x*2+3]) >> 3;
  1082. }
  1083. }
  1084. }
  1085. break;
  1086. case 3:
  1087. for (int z = 0; z < depthOut; ++z)
  1088. {
  1089. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*3];
  1090. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*3];
  1091. for (int y = 0; y < heightOut; ++y)
  1092. {
  1093. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*3];
  1094. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*3];
  1095. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*3];
  1096. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*3];
  1097. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*3 + y*widthOut*3];
  1098. for (int x = 0; x < widthOut*3; x += 3)
  1099. {
  1100. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+3] + inOuterLower[x*2] + inOuterLower[x*2+3] +
  1101. inInnerUpper[x*2] + inInnerUpper[x*2+3] + inInnerLower[x*2] + inInnerLower[x*2+3]) >> 3;
  1102. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+4] + inOuterLower[x*2+1] + inOuterLower[x*2+4] +
  1103. inInnerUpper[x*2+1] + inInnerUpper[x*2+4] + inInnerLower[x*2+1] + inInnerLower[x*2+4]) >> 3;
  1104. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+5] + inOuterLower[x*2+2] + inOuterLower[x*2+5] +
  1105. inInnerUpper[x*2+2] + inInnerUpper[x*2+5] + inInnerLower[x*2+2] + inInnerLower[x*2+5]) >> 3;
  1106. }
  1107. }
  1108. }
  1109. break;
  1110. case 4:
  1111. for (int z = 0; z < depthOut; ++z)
  1112. {
  1113. const unsigned char* inOuter = &pixelDataIn[(z*2)*width_*height_*4];
  1114. const unsigned char* inInner = &pixelDataIn[(z*2+1)*width_*height_*4];
  1115. for (int y = 0; y < heightOut; ++y)
  1116. {
  1117. const unsigned char* inOuterUpper = &inOuter[(y*2)*width_*4];
  1118. const unsigned char* inOuterLower = &inOuter[(y*2+1)*width_*4];
  1119. const unsigned char* inInnerUpper = &inInner[(y*2)*width_*4];
  1120. const unsigned char* inInnerLower = &inInner[(y*2+1)*width_*4];
  1121. unsigned char* out = &pixelDataOut[z*widthOut*heightOut*4 + y*widthOut*4];
  1122. for (int x = 0; x < widthOut*4; x += 4)
  1123. {
  1124. out[x] = ((unsigned)inOuterUpper[x*2] + inOuterUpper[x*2+4] + inOuterLower[x*2] + inOuterLower[x*2+4] +
  1125. inInnerUpper[x*2] + inInnerUpper[x*2+4] + inInnerLower[x*2] + inInnerLower[x*2+4]) >> 3;
  1126. out[x+1] = ((unsigned)inOuterUpper[x*2+1] + inOuterUpper[x*2+5] + inOuterLower[x*2+1] + inOuterLower[x*2+5] +
  1127. inInnerUpper[x*2+1] + inInnerUpper[x*2+5] + inInnerLower[x*2+1] + inInnerLower[x*2+5]) >> 3;
  1128. out[x+2] = ((unsigned)inOuterUpper[x*2+2] + inOuterUpper[x*2+6] + inOuterLower[x*2+2] + inOuterLower[x*2+6] +
  1129. inInnerUpper[x*2+2] + inInnerUpper[x*2+6] + inInnerLower[x*2+2] + inInnerLower[x*2+6]) >> 3;
  1130. }
  1131. }
  1132. }
  1133. break;
  1134. }
  1135. }
  1136. return mipImage;
  1137. }
  1138. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1139. {
  1140. CompressedLevel level;
  1141. if (compressedFormat_ == CF_NONE)
  1142. {
  1143. LOGERROR("Image is not compressed");
  1144. return level;
  1145. }
  1146. if (index >= numCompressedLevels_)
  1147. {
  1148. LOGERROR("Compressed image mip level out of bounds");
  1149. return level;
  1150. }
  1151. level.format_ = compressedFormat_;
  1152. level.width_ = width_;
  1153. level.height_ = height_;
  1154. level.depth_ = depth_;
  1155. if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1156. {
  1157. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1158. unsigned i = 0;
  1159. unsigned offset = 0;
  1160. for (;;)
  1161. {
  1162. if (!level.width_)
  1163. level.width_ = 1;
  1164. if (!level.height_)
  1165. level.height_ = 1;
  1166. if (!level.depth_)
  1167. level.depth_ = 1;
  1168. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1169. level.rows_ = ((level.height_ + 3) / 4);
  1170. level.data_ = data_.Get() + offset;
  1171. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1172. if (offset + level.dataSize_ > GetMemoryUse())
  1173. {
  1174. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1175. " Datasize: " + String(GetMemoryUse()));
  1176. level.data_ = 0;
  1177. return level;
  1178. }
  1179. if (i == index)
  1180. return level;
  1181. offset += level.dataSize_;
  1182. level.width_ /= 2;
  1183. level.height_ /= 2;
  1184. level.depth_ /= 2;
  1185. ++i;
  1186. }
  1187. }
  1188. else
  1189. {
  1190. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1191. unsigned i = 0;
  1192. unsigned offset = 0;
  1193. for (;;)
  1194. {
  1195. if (!level.width_)
  1196. level.width_ = 1;
  1197. if (!level.height_)
  1198. level.height_ = 1;
  1199. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1200. int dataHeight = Max(level.height_, 8);
  1201. level.data_ = data_.Get() + offset;
  1202. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1203. level.rows_ = dataHeight;
  1204. level.rowSize_ = level.dataSize_ / level.rows_;
  1205. if (offset + level.dataSize_ > GetMemoryUse())
  1206. {
  1207. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1208. " Datasize: " + String(GetMemoryUse()));
  1209. level.data_ = 0;
  1210. return level;
  1211. }
  1212. if (i == index)
  1213. return level;
  1214. offset += level.dataSize_;
  1215. level.width_ /= 2;
  1216. level.height_ /= 2;
  1217. ++i;
  1218. }
  1219. }
  1220. }
  1221. Image* Image::GetSubimage(const IntRect& rect) const
  1222. {
  1223. if (!data_)
  1224. return 0;
  1225. if (depth_ > 1)
  1226. {
  1227. LOGERROR("Subimage not supported for 3D images");
  1228. return 0;
  1229. }
  1230. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1231. {
  1232. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1233. return 0;
  1234. }
  1235. if (!IsCompressed())
  1236. {
  1237. int x = rect.left_;
  1238. int y = rect.top_;
  1239. int width = rect.Width();
  1240. int height = rect.Height();
  1241. Image* image = new Image(context_);
  1242. image->SetSize(width, height, components_);
  1243. unsigned char* dest = image->GetData();
  1244. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1245. for (int i = 0; i < height; ++i)
  1246. {
  1247. memcpy(dest, src, width * components_);
  1248. dest += width * components_;
  1249. src += width_ * components_;
  1250. }
  1251. return image;
  1252. }
  1253. else
  1254. {
  1255. // Pad the region to be a multiple of block size
  1256. IntRect paddedRect = rect;
  1257. paddedRect.left_ = (rect.left_ / 4) * 4;
  1258. paddedRect.top_ = (rect.top_ / 4) * 4;
  1259. paddedRect.right_ = (rect.right_ / 4) * 4;
  1260. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1261. IntRect currentRect = paddedRect;
  1262. PODVector<unsigned char> subimageData;
  1263. unsigned subimageLevels = 0;
  1264. // Save as many mips as possible until the next mip would cross a block boundary
  1265. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1266. {
  1267. CompressedLevel level = GetCompressedLevel(i);
  1268. if (!level.data_)
  1269. break;
  1270. // Mips are stored continuously
  1271. unsigned destStartOffset = subimageData.Size();
  1272. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1273. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1274. if (!destSize)
  1275. break;
  1276. subimageData.Resize(destStartOffset + destSize);
  1277. unsigned char* dest = &subimageData[destStartOffset];
  1278. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1279. {
  1280. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1281. memcpy(dest, src, destRowSize);
  1282. dest += destRowSize;
  1283. }
  1284. ++subimageLevels;
  1285. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1286. break;
  1287. else
  1288. {
  1289. currentRect.left_ /= 2;
  1290. currentRect.right_ /= 2;
  1291. currentRect.top_ /= 2;
  1292. currentRect.bottom_ /= 2;
  1293. }
  1294. }
  1295. if (!subimageLevels)
  1296. {
  1297. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1298. return 0;
  1299. }
  1300. Image* image = new Image(context_);
  1301. image->width_ = paddedRect.Width();
  1302. image->height_ = paddedRect.Height();
  1303. image->depth_ = 1;
  1304. image->compressedFormat_ = compressedFormat_;
  1305. image->numCompressedLevels_ = subimageLevels;
  1306. image->components_ = components_;
  1307. image->data_ = new unsigned char[subimageData.Size()];
  1308. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1309. image->SetMemoryUse(subimageData.Size());
  1310. return image;
  1311. }
  1312. }
  1313. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1314. {
  1315. if (!data_)
  1316. return 0;
  1317. if (depth_ > 1)
  1318. {
  1319. LOGERROR("Can not get SDL surface from 3D image");
  1320. return 0;
  1321. }
  1322. if (IsCompressed())
  1323. {
  1324. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1325. return 0;
  1326. }
  1327. if (components_ < 3)
  1328. {
  1329. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1330. return 0;
  1331. }
  1332. IntRect imageRect = rect;
  1333. // Use full image if illegal rect
  1334. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1335. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1336. {
  1337. imageRect.left_ = 0;
  1338. imageRect.top_ = 0;
  1339. imageRect.right_ = width_;
  1340. imageRect.bottom_ = height_;
  1341. }
  1342. int imageWidth = width_;
  1343. int width = imageRect.Width();
  1344. int height = imageRect.Height();
  1345. // Assume little-endian for all the supported platforms
  1346. unsigned rMask = 0x000000ff;
  1347. unsigned gMask = 0x0000ff00;
  1348. unsigned bMask = 0x00ff0000;
  1349. unsigned aMask = 0xff000000;
  1350. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1351. if (surface)
  1352. {
  1353. SDL_LockSurface(surface);
  1354. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1355. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1356. for (int i = 0; i < height; ++i)
  1357. {
  1358. memcpy(destination, source, components_ * width);
  1359. destination += surface->pitch;
  1360. source += components_ * imageWidth;
  1361. }
  1362. SDL_UnlockSurface(surface);
  1363. }
  1364. else
  1365. LOGERROR("Failed to create SDL surface from image " + GetName());
  1366. return surface;
  1367. }
  1368. void Image::PrecalculateLevels()
  1369. {
  1370. if (!data_ || IsCompressed())
  1371. return;
  1372. PROFILE(PrecalculateImageMipLevels);
  1373. nextLevel_.Reset();
  1374. if (width_ > 1 || height_ > 1)
  1375. {
  1376. SharedPtr<Image> current = GetNextLevel();
  1377. nextLevel_ = current;
  1378. while (current && (current->width_ > 1 || current->height_ > 1))
  1379. {
  1380. current->nextLevel_ = current->GetNextLevel();
  1381. current = current->nextLevel_;
  1382. }
  1383. }
  1384. }
  1385. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1386. {
  1387. unsigned dataSize = source.GetSize();
  1388. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1389. source.Read(buffer.Get(), dataSize);
  1390. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, (int *)&components, 0);
  1391. }
  1392. void Image::FreeImageData(unsigned char* pixelData)
  1393. {
  1394. if (!pixelData)
  1395. return;
  1396. stbi_image_free(pixelData);
  1397. }
  1398. }