1
0

CCImage.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "platform/CCImage.h"
  22. #include <string>
  23. #include <ctype.h>
  24. #include "base/CCData.h"
  25. #include "base/ccConfig.h" // CC_USE_JPEG, CC_USE_TIFF, CC_USE_WEBP
  26. extern "C"
  27. {
  28. // To resolve link error when building 32bits with Xcode 6.
  29. // More information please refer to the discussion in https://github.com/cocos2d/cocos2d-x/pull/6986
  30. #if defined (__unix) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  31. #ifndef __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
  32. #define __ENABLE_COMPATIBILITY_WITH_UNIX_2003__
  33. #include <stdio.h>
  34. #include <dirent.h>
  35. FILE *fopen$UNIX2003( const char *filename, const char *mode )
  36. {
  37. return fopen(filename, mode);
  38. }
  39. size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
  40. {
  41. return fwrite(a, b, c, d);
  42. }
  43. int fputs$UNIX2003(const char *res1, FILE *res2){
  44. return fputs(res1,res2);
  45. }
  46. char *strerror$UNIX2003( int errnum )
  47. {
  48. return strerror(errnum);
  49. }
  50. DIR * opendir$INODE64$UNIX2003( char * dirName )
  51. {
  52. return opendir( dirName );
  53. }
  54. DIR * opendir$INODE64( char * dirName )
  55. {
  56. return opendir( dirName );
  57. }
  58. int closedir$UNIX2003(DIR * dir)
  59. {
  60. return closedir(dir);
  61. }
  62. struct dirent * readdir$INODE64( DIR * dir )
  63. {
  64. return readdir( dir );
  65. }
  66. #endif
  67. #endif
  68. #if CC_USE_PNG
  69. #include "png.h"
  70. #endif //CC_USE_PNG
  71. #if CC_USE_TIFF
  72. #include "tiffio.h"
  73. #endif //CC_USE_TIFF
  74. #include "base/etc1.h"
  75. #if CC_USE_JPEG
  76. #include "jpeglib.h"
  77. #endif // CC_USE_JPEG
  78. }
  79. #include "base/s3tc.h"
  80. #include "base/atitc.h"
  81. #include "base/pvr.h"
  82. #include "base/TGAlib.h"
  83. #if CC_USE_WEBP
  84. #include "decode.h"
  85. #endif // CC_USE_WEBP
  86. #include "base/ccMacros.h"
  87. #include "platform/CCCommon.h"
  88. #include "platform/CCStdC.h"
  89. #include "platform/CCFileUtils.h"
  90. #include "base/CCConfiguration.h"
  91. #include "base/ccUtils.h"
  92. #include "base/ZipUtils.h"
  93. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  94. #include "platform/android/CCFileUtils-android.h"
  95. #endif
  96. #define CC_GL_ATC_RGB_AMD 0x8C92
  97. #define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
  98. #define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
  99. NS_CC_BEGIN
  100. //////////////////////////////////////////////////////////////////////////
  101. //struct and data for pvr structure
  102. namespace
  103. {
  104. static const int PVR_TEXTURE_FLAG_TYPE_MASK = 0xff;
  105. static bool _PVRHaveAlphaPremultiplied = false;
  106. // Values taken from PVRTexture.h from http://www.imgtec.com
  107. enum class PVR2TextureFlag
  108. {
  109. Mipmap = (1<<8), // has mip map levels
  110. Twiddle = (1<<9), // is twiddled
  111. Bumpmap = (1<<10), // has normals encoded for a bump map
  112. Tiling = (1<<11), // is bordered for tiled pvr
  113. Cubemap = (1<<12), // is a cubemap/skybox
  114. FalseMipCol = (1<<13), // are there false colored MIP levels
  115. Volume = (1<<14), // is this a volume texture
  116. Alpha = (1<<15), // v2.1 is there transparency info in the texture
  117. VerticalFlip = (1<<16), // v2.1 is the texture vertically flipped
  118. };
  119. enum class PVR3TextureFlag
  120. {
  121. PremultipliedAlpha = (1<<1) // has premultiplied alpha
  122. };
  123. static const char gPVRTexIdentifier[5] = "PVR!";
  124. // v2
  125. enum class PVR2TexturePixelFormat : unsigned char
  126. {
  127. RGBA4444 = 0x10,
  128. RGBA5551,
  129. RGBA8888,
  130. RGB565,
  131. RGB555, // unsupported
  132. RGB888,
  133. I8,
  134. AI88,
  135. PVRTC2BPP_RGBA,
  136. PVRTC4BPP_RGBA,
  137. BGRA8888,
  138. A8,
  139. };
  140. // v3
  141. enum class PVR3TexturePixelFormat : uint64_t
  142. {
  143. PVRTC2BPP_RGB = 0ULL,
  144. PVRTC2BPP_RGBA = 1ULL,
  145. PVRTC4BPP_RGB = 2ULL,
  146. PVRTC4BPP_RGBA = 3ULL,
  147. PVRTC2_2BPP_RGBA = 4ULL,
  148. PVRTC2_4BPP_RGBA = 5ULL,
  149. ETC1 = 6ULL,
  150. DXT1 = 7ULL,
  151. DXT2 = 8ULL,
  152. DXT3 = 9ULL,
  153. DXT4 = 10ULL,
  154. DXT5 = 11ULL,
  155. BC1 = 7ULL,
  156. BC2 = 9ULL,
  157. BC3 = 11ULL,
  158. BC4 = 12ULL,
  159. BC5 = 13ULL,
  160. BC6 = 14ULL,
  161. BC7 = 15ULL,
  162. UYVY = 16ULL,
  163. YUY2 = 17ULL,
  164. BW1bpp = 18ULL,
  165. R9G9B9E5 = 19ULL,
  166. RGBG8888 = 20ULL,
  167. GRGB8888 = 21ULL,
  168. ETC2_RGB = 22ULL,
  169. ETC2_RGBA = 23ULL,
  170. ETC2_RGBA1 = 24ULL,
  171. EAC_R11_Unsigned = 25ULL,
  172. EAC_R11_Signed = 26ULL,
  173. EAC_RG11_Unsigned = 27ULL,
  174. EAC_RG11_Signed = 28ULL,
  175. BGRA8888 = 0x0808080861726762ULL,
  176. RGBA8888 = 0x0808080861626772ULL,
  177. RGBA4444 = 0x0404040461626772ULL,
  178. RGBA5551 = 0x0105050561626772ULL,
  179. RGB565 = 0x0005060500626772ULL,
  180. RGB888 = 0x0008080800626772ULL,
  181. A8 = 0x0000000800000061ULL,
  182. L8 = 0x000000080000006cULL,
  183. LA88 = 0x000008080000616cULL,
  184. };
  185. // v2
  186. typedef const std::map<PVR2TexturePixelFormat, Texture2D::PixelFormat> _pixel2_formathash;
  187. static const _pixel2_formathash::value_type v2_pixel_formathash_value[] =
  188. {
  189. _pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888),
  190. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888),
  191. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444),
  192. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1),
  193. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565),
  194. _pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888),
  195. _pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, Texture2D::PixelFormat::A8),
  196. _pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, Texture2D::PixelFormat::I8),
  197. _pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, Texture2D::PixelFormat::AI88),
  198. _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A),
  199. _pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A),
  200. };
  201. static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]);
  202. static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS);
  203. // v3
  204. typedef const std::map<PVR3TexturePixelFormat, Texture2D::PixelFormat> _pixel3_formathash;
  205. static _pixel3_formathash::value_type v3_pixel_formathash_value[] =
  206. {
  207. _pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, Texture2D::PixelFormat::BGRA8888),
  208. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, Texture2D::PixelFormat::RGBA8888),
  209. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, Texture2D::PixelFormat::RGBA4444),
  210. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, Texture2D::PixelFormat::RGB5A1),
  211. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, Texture2D::PixelFormat::RGB565),
  212. _pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, Texture2D::PixelFormat::RGB888),
  213. _pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, Texture2D::PixelFormat::A8),
  214. _pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, Texture2D::PixelFormat::I8),
  215. _pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, Texture2D::PixelFormat::AI88),
  216. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, Texture2D::PixelFormat::PVRTC2),
  217. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, Texture2D::PixelFormat::PVRTC2A),
  218. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, Texture2D::PixelFormat::PVRTC4),
  219. _pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, Texture2D::PixelFormat::PVRTC4A),
  220. _pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, Texture2D::PixelFormat::ETC),
  221. };
  222. static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]);
  223. static const _pixel3_formathash v3_pixel_formathash(v3_pixel_formathash_value, v3_pixel_formathash_value + PVR3_MAX_TABLE_ELEMENTS);
  224. typedef struct _PVRTexHeader
  225. {
  226. unsigned int headerLength;
  227. unsigned int height;
  228. unsigned int width;
  229. unsigned int numMipmaps;
  230. unsigned int flags;
  231. unsigned int dataLength;
  232. unsigned int bpp;
  233. unsigned int bitmaskRed;
  234. unsigned int bitmaskGreen;
  235. unsigned int bitmaskBlue;
  236. unsigned int bitmaskAlpha;
  237. unsigned int pvrTag;
  238. unsigned int numSurfs;
  239. } PVRv2TexHeader;
  240. #ifdef _MSC_VER
  241. #pragma pack(push,1)
  242. #endif
  243. typedef struct
  244. {
  245. uint32_t version;
  246. uint32_t flags;
  247. uint64_t pixelFormat;
  248. uint32_t colorSpace;
  249. uint32_t channelType;
  250. uint32_t height;
  251. uint32_t width;
  252. uint32_t depth;
  253. uint32_t numberOfSurfaces;
  254. uint32_t numberOfFaces;
  255. uint32_t numberOfMipmaps;
  256. uint32_t metadataLength;
  257. #ifdef _MSC_VER
  258. } PVRv3TexHeader;
  259. #pragma pack(pop)
  260. #else
  261. } __attribute__((packed)) PVRv3TexHeader;
  262. #endif
  263. }
  264. //pvr structure end
  265. //////////////////////////////////////////////////////////////////////////
  266. //struct and data for s3tc(dds) struct
  267. namespace
  268. {
  269. struct DDColorKey
  270. {
  271. uint32_t colorSpaceLowValue;
  272. uint32_t colorSpaceHighValue;
  273. };
  274. struct DDSCaps
  275. {
  276. uint32_t caps;
  277. uint32_t caps2;
  278. uint32_t caps3;
  279. uint32_t caps4;
  280. };
  281. struct DDPixelFormat
  282. {
  283. uint32_t size;
  284. uint32_t flags;
  285. uint32_t fourCC;
  286. uint32_t RGBBitCount;
  287. uint32_t RBitMask;
  288. uint32_t GBitMask;
  289. uint32_t BBitMask;
  290. uint32_t ABitMask;
  291. };
  292. struct DDSURFACEDESC2
  293. {
  294. uint32_t size;
  295. uint32_t flags;
  296. uint32_t height;
  297. uint32_t width;
  298. union
  299. {
  300. uint32_t pitch;
  301. uint32_t linearSize;
  302. } DUMMYUNIONNAMEN1;
  303. union
  304. {
  305. uint32_t backBufferCount;
  306. uint32_t depth;
  307. } DUMMYUNIONNAMEN5;
  308. union
  309. {
  310. uint32_t mipMapCount;
  311. uint32_t refreshRate;
  312. uint32_t srcVBHandle;
  313. } DUMMYUNIONNAMEN2;
  314. uint32_t alphaBitDepth;
  315. uint32_t reserved;
  316. uint32_t surface;
  317. union
  318. {
  319. DDColorKey ddckCKDestOverlay;
  320. uint32_t emptyFaceColor;
  321. } DUMMYUNIONNAMEN3;
  322. DDColorKey ddckCKDestBlt;
  323. DDColorKey ddckCKSrcOverlay;
  324. DDColorKey ddckCKSrcBlt;
  325. union
  326. {
  327. DDPixelFormat ddpfPixelFormat;
  328. uint32_t FVF;
  329. } DUMMYUNIONNAMEN4;
  330. DDSCaps ddsCaps;
  331. uint32_t textureStage;
  332. } ;
  333. #pragma pack(push,1)
  334. struct S3TCTexHeader
  335. {
  336. char fileCode[4];
  337. DDSURFACEDESC2 ddsd;
  338. };
  339. #pragma pack(pop)
  340. }
  341. //s3tc struct end
  342. //////////////////////////////////////////////////////////////////////////
  343. //struct and data for atitc(ktx) struct
  344. namespace
  345. {
  346. struct ATITCTexHeader
  347. {
  348. //HEADER
  349. char identifier[12];
  350. uint32_t endianness;
  351. uint32_t glType;
  352. uint32_t glTypeSize;
  353. uint32_t glFormat;
  354. uint32_t glInternalFormat;
  355. uint32_t glBaseInternalFormat;
  356. uint32_t pixelWidth;
  357. uint32_t pixelHeight;
  358. uint32_t pixelDepth;
  359. uint32_t numberOfArrayElements;
  360. uint32_t numberOfFaces;
  361. uint32_t numberOfMipmapLevels;
  362. uint32_t bytesOfKeyValueData;
  363. };
  364. }
  365. //atitc struct end
  366. //////////////////////////////////////////////////////////////////////////
  367. namespace
  368. {
  369. typedef struct
  370. {
  371. const unsigned char * data;
  372. ssize_t size;
  373. int offset;
  374. }tImageSource;
  375. #ifdef CC_USE_PNG
  376. static void pngReadCallback(png_structp png_ptr, png_bytep data, png_size_t length)
  377. {
  378. tImageSource* isource = (tImageSource*)png_get_io_ptr(png_ptr);
  379. if((int)(isource->offset + length) <= isource->size)
  380. {
  381. memcpy(data, isource->data+isource->offset, length);
  382. isource->offset += length;
  383. }
  384. else
  385. {
  386. png_error(png_ptr, "pngReaderCallback failed");
  387. }
  388. }
  389. #endif //CC_USE_PNG
  390. }
  391. Texture2D::PixelFormat getDevicePixelFormat(Texture2D::PixelFormat format)
  392. {
  393. switch (format) {
  394. case Texture2D::PixelFormat::PVRTC4:
  395. case Texture2D::PixelFormat::PVRTC4A:
  396. case Texture2D::PixelFormat::PVRTC2:
  397. case Texture2D::PixelFormat::PVRTC2A:
  398. if(Configuration::getInstance()->supportsPVRTC())
  399. return format;
  400. else
  401. return Texture2D::PixelFormat::RGBA8888;
  402. case Texture2D::PixelFormat::ETC:
  403. if(Configuration::getInstance()->supportsETC())
  404. return format;
  405. else
  406. return Texture2D::PixelFormat::RGB888;
  407. default:
  408. return format;
  409. }
  410. }
  411. //////////////////////////////////////////////////////////////////////////
  412. // Implement Image
  413. //////////////////////////////////////////////////////////////////////////
  414. bool Image::PNG_PREMULTIPLIED_ALPHA_ENABLED = true;
  415. Image::Image()
  416. : _data(nullptr)
  417. , _dataLen(0)
  418. , _width(0)
  419. , _height(0)
  420. , _unpack(false)
  421. , _fileType(Format::UNKNOWN)
  422. , _renderFormat(Texture2D::PixelFormat::NONE)
  423. , _numberOfMipmaps(0)
  424. , _hasPremultipliedAlpha(false)
  425. {
  426. }
  427. Image::~Image()
  428. {
  429. if(_unpack)
  430. {
  431. for (int i = 0; i < _numberOfMipmaps; ++i)
  432. CC_SAFE_DELETE_ARRAY(_mipmaps[i].address);
  433. }
  434. else
  435. CC_SAFE_FREE(_data);
  436. }
  437. bool Image::initWithImageFile(const std::string& path)
  438. {
  439. bool ret = false;
  440. _filePath = FileUtils::getInstance()->fullPathForFilename(path);
  441. Data data = FileUtils::getInstance()->getDataFromFile(_filePath);
  442. if (!data.isNull())
  443. {
  444. ret = initWithImageData(data.getBytes(), data.getSize());
  445. }
  446. return ret;
  447. }
  448. bool Image::initWithImageFileThreadSafe(const std::string& fullpath)
  449. {
  450. bool ret = false;
  451. _filePath = fullpath;
  452. Data data = FileUtils::getInstance()->getDataFromFile(fullpath);
  453. if (!data.isNull())
  454. {
  455. ret = initWithImageData(data.getBytes(), data.getSize());
  456. }
  457. return ret;
  458. }
  459. bool Image::initWithImageData(const unsigned char * data, ssize_t dataLen)
  460. {
  461. bool ret = false;
  462. do
  463. {
  464. CC_BREAK_IF(! data || dataLen <= 0);
  465. unsigned char* unpackedData = nullptr;
  466. ssize_t unpackedLen = 0;
  467. //detect and unzip the compress file
  468. if (ZipUtils::isCCZBuffer(data, dataLen))
  469. {
  470. unpackedLen = ZipUtils::inflateCCZBuffer(data, dataLen, &unpackedData);
  471. }
  472. else if (ZipUtils::isGZipBuffer(data, dataLen))
  473. {
  474. unpackedLen = ZipUtils::inflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
  475. }
  476. else
  477. {
  478. unpackedData = const_cast<unsigned char*>(data);
  479. unpackedLen = dataLen;
  480. }
  481. _fileType = detectFormat(unpackedData, unpackedLen);
  482. switch (_fileType)
  483. {
  484. case Format::PNG:
  485. ret = initWithPngData(unpackedData, unpackedLen);
  486. break;
  487. case Format::JPG:
  488. ret = initWithJpgData(unpackedData, unpackedLen);
  489. break;
  490. case Format::TIFF:
  491. ret = initWithTiffData(unpackedData, unpackedLen);
  492. break;
  493. case Format::WEBP:
  494. ret = initWithWebpData(unpackedData, unpackedLen);
  495. break;
  496. case Format::PVR:
  497. ret = initWithPVRData(unpackedData, unpackedLen);
  498. break;
  499. case Format::ETC:
  500. ret = initWithETCData(unpackedData, unpackedLen);
  501. break;
  502. case Format::S3TC:
  503. ret = initWithS3TCData(unpackedData, unpackedLen);
  504. break;
  505. case Format::ATITC:
  506. ret = initWithATITCData(unpackedData, unpackedLen);
  507. break;
  508. default:
  509. {
  510. // load and detect image format
  511. tImageTGA* tgaData = tgaLoadBuffer(unpackedData, unpackedLen);
  512. if (tgaData != nullptr && tgaData->status == TGA_OK)
  513. {
  514. ret = initWithTGAData(tgaData);
  515. }
  516. else
  517. {
  518. CCLOG("cocos2d: unsupported image format!");
  519. }
  520. free(tgaData);
  521. break;
  522. }
  523. }
  524. if(unpackedData != data)
  525. {
  526. free(unpackedData);
  527. }
  528. } while (0);
  529. return ret;
  530. }
  531. bool Image::isPng(const unsigned char * data, ssize_t dataLen)
  532. {
  533. if (dataLen <= 8)
  534. {
  535. return false;
  536. }
  537. static const unsigned char PNG_SIGNATURE[] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a};
  538. return memcmp(PNG_SIGNATURE, data, sizeof(PNG_SIGNATURE)) == 0;
  539. }
  540. bool Image::isEtc(const unsigned char * data, ssize_t /*dataLen*/)
  541. {
  542. return etc1_pkm_is_valid((etc1_byte*)data) ? true : false;
  543. }
  544. bool Image::isS3TC(const unsigned char * data, ssize_t /*dataLen*/)
  545. {
  546. S3TCTexHeader *header = (S3TCTexHeader *)data;
  547. if (strncmp(header->fileCode, "DDS", 3) != 0)
  548. {
  549. return false;
  550. }
  551. return true;
  552. }
  553. bool Image::isATITC(const unsigned char *data, ssize_t /*dataLen*/)
  554. {
  555. ATITCTexHeader *header = (ATITCTexHeader *)data;
  556. if (strncmp(&header->identifier[1], "KTX", 3) != 0)
  557. {
  558. return false;
  559. }
  560. return true;
  561. }
  562. bool Image::isJpg(const unsigned char * data, ssize_t dataLen)
  563. {
  564. if (dataLen <= 4)
  565. {
  566. return false;
  567. }
  568. static const unsigned char JPG_SOI[] = {0xFF, 0xD8};
  569. return memcmp(data, JPG_SOI, 2) == 0;
  570. }
  571. bool Image::isTiff(const unsigned char * data, ssize_t dataLen)
  572. {
  573. if (dataLen <= 4)
  574. {
  575. return false;
  576. }
  577. static const char* TIFF_II = "II";
  578. static const char* TIFF_MM = "MM";
  579. return (memcmp(data, TIFF_II, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 42 && *(static_cast<const unsigned char*>(data) + 3) == 0) ||
  580. (memcmp(data, TIFF_MM, 2) == 0 && *(static_cast<const unsigned char*>(data) + 2) == 0 && *(static_cast<const unsigned char*>(data) + 3) == 42);
  581. }
  582. bool Image::isWebp(const unsigned char * data, ssize_t dataLen)
  583. {
  584. if (dataLen <= 12)
  585. {
  586. return false;
  587. }
  588. static const char* WEBP_RIFF = "RIFF";
  589. static const char* WEBP_WEBP = "WEBP";
  590. return memcmp(data, WEBP_RIFF, 4) == 0
  591. && memcmp(static_cast<const unsigned char*>(data) + 8, WEBP_WEBP, 4) == 0;
  592. }
  593. bool Image::isPvr(const unsigned char * data, ssize_t dataLen)
  594. {
  595. if (static_cast<size_t>(dataLen) < sizeof(PVRv2TexHeader) || static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
  596. {
  597. return false;
  598. }
  599. const PVRv2TexHeader* headerv2 = static_cast<const PVRv2TexHeader*>(static_cast<const void*>(data));
  600. const PVRv3TexHeader* headerv3 = static_cast<const PVRv3TexHeader*>(static_cast<const void*>(data));
  601. return memcmp(&headerv2->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) == 0 || CC_SWAP_INT32_BIG_TO_HOST(headerv3->version) == 0x50565203;
  602. }
  603. Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen)
  604. {
  605. if (isPng(data, dataLen))
  606. {
  607. return Format::PNG;
  608. }
  609. else if (isJpg(data, dataLen))
  610. {
  611. return Format::JPG;
  612. }
  613. else if (isTiff(data, dataLen))
  614. {
  615. return Format::TIFF;
  616. }
  617. else if (isWebp(data, dataLen))
  618. {
  619. return Format::WEBP;
  620. }
  621. else if (isPvr(data, dataLen))
  622. {
  623. return Format::PVR;
  624. }
  625. else if (isEtc(data, dataLen))
  626. {
  627. return Format::ETC;
  628. }
  629. else if (isS3TC(data, dataLen))
  630. {
  631. return Format::S3TC;
  632. }
  633. else if (isATITC(data, dataLen))
  634. {
  635. return Format::ATITC;
  636. }
  637. else
  638. {
  639. return Format::UNKNOWN;
  640. }
  641. }
  642. int Image::getBitPerPixel()
  643. {
  644. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).bpp;
  645. }
  646. bool Image::hasAlpha()
  647. {
  648. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).alpha;
  649. }
  650. bool Image::isCompressed()
  651. {
  652. return Texture2D::getPixelFormatInfoMap().at(_renderFormat).compressed;
  653. }
  654. namespace
  655. {
  656. /*
  657. * ERROR HANDLING:
  658. *
  659. * The JPEG library's standard error handler (jerror.c) is divided into
  660. * several "methods" which you can override individually. This lets you
  661. * adjust the behavior without duplicating a lot of code, which you might
  662. * have to update with each future release.
  663. *
  664. * We override the "error_exit" method so that control is returned to the
  665. * library's caller when a fatal error occurs, rather than calling exit()
  666. * as the standard error_exit method does.
  667. *
  668. * We use C's setjmp/longjmp facility to return control. This means that the
  669. * routine which calls the JPEG library must first execute a setjmp() call to
  670. * establish the return point. We want the replacement error_exit to do a
  671. * longjmp(). But we need to make the setjmp buffer accessible to the
  672. * error_exit routine. To do this, we make a private extension of the
  673. * standard JPEG error handler object. (If we were using C++, we'd say we
  674. * were making a subclass of the regular error handler.)
  675. *
  676. * Here's the extended error handler struct:
  677. */
  678. #if CC_USE_JPEG
  679. struct MyErrorMgr
  680. {
  681. struct jpeg_error_mgr pub; /* "public" fields */
  682. jmp_buf setjmp_buffer; /* for return to caller */
  683. };
  684. typedef struct MyErrorMgr * MyErrorPtr;
  685. /*
  686. * Here's the routine that will replace the standard error_exit method:
  687. */
  688. METHODDEF(void)
  689. myErrorExit(j_common_ptr cinfo)
  690. {
  691. /* cinfo->err really points to a MyErrorMgr struct, so coerce pointer */
  692. MyErrorPtr myerr = (MyErrorPtr) cinfo->err;
  693. /* Always display the message. */
  694. /* We could postpone this until after returning, if we chose. */
  695. /* internal message function can't show error message in some platforms, so we rewrite it here.
  696. * edit it if has version conflict.
  697. */
  698. //(*cinfo->err->output_message) (cinfo);
  699. char buffer[JMSG_LENGTH_MAX];
  700. (*cinfo->err->format_message) (cinfo, buffer);
  701. CCLOG("jpeg error: %s", buffer);
  702. /* Return control to the setjmp point */
  703. longjmp(myerr->setjmp_buffer, 1);
  704. }
  705. #endif // CC_USE_JPEG
  706. }
  707. #if CC_USE_WIC
  708. bool Image::decodeWithWIC(const unsigned char *data, ssize_t dataLen)
  709. {
  710. bool bRet = false;
  711. WICImageLoader img;
  712. if (img.decodeImageData(data, dataLen))
  713. {
  714. _width = img.getWidth();
  715. _height = img.getHeight();
  716. WICPixelFormatGUID format = img.getPixelFormat();
  717. if (memcmp(&format, &GUID_WICPixelFormat8bppGray, sizeof(WICPixelFormatGUID)) == 0)
  718. {
  719. _renderFormat = Texture2D::PixelFormat::I8;
  720. }
  721. if (memcmp(&format, &GUID_WICPixelFormat8bppAlpha, sizeof(WICPixelFormatGUID)) == 0)
  722. {
  723. _renderFormat = Texture2D::PixelFormat::AI88;
  724. }
  725. if (memcmp(&format, &GUID_WICPixelFormat24bppRGB, sizeof(WICPixelFormatGUID)) == 0)
  726. {
  727. _renderFormat = Texture2D::PixelFormat::RGB888;
  728. }
  729. if (memcmp(&format, &GUID_WICPixelFormat32bppRGBA, sizeof(WICPixelFormatGUID)) == 0)
  730. {
  731. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  732. }
  733. if (memcmp(&format, &GUID_WICPixelFormat32bppBGRA, sizeof(WICPixelFormatGUID)) == 0)
  734. {
  735. _renderFormat = Texture2D::PixelFormat::BGRA8888;
  736. }
  737. _dataLen = img.getImageDataSize();
  738. CCASSERT(_dataLen > 0, "Image: Decompressed data length is invalid");
  739. _data = new (std::nothrow) unsigned char[_dataLen];
  740. bRet = (img.getImageData(_data, _dataLen) > 0);
  741. if (_renderFormat == Texture2D::PixelFormat::RGBA8888) {
  742. premultipliedAlpha();
  743. }
  744. }
  745. return bRet;
  746. }
  747. bool Image::encodeWithWIC(const std::string& filePath, bool isToRGB, GUID containerFormat)
  748. {
  749. // Save formats supported by WIC
  750. WICPixelFormatGUID targetFormat = isToRGB ? GUID_WICPixelFormat24bppBGR : GUID_WICPixelFormat32bppBGRA;
  751. unsigned char *pSaveData = nullptr;
  752. int saveLen = _dataLen;
  753. int bpp = 4;
  754. if (targetFormat == GUID_WICPixelFormat24bppBGR && _renderFormat == Texture2D::PixelFormat::RGBA8888)
  755. {
  756. bpp = 3;
  757. saveLen = _width * _height * bpp;
  758. pSaveData = new (std::nothrow) unsigned char[saveLen];
  759. int indL = 0, indR = 0;
  760. while (indL < saveLen && indR < _dataLen)
  761. {
  762. memcpy(&pSaveData[indL], &_data[indR], 3);
  763. indL += 3;
  764. indR += 4;
  765. }
  766. }
  767. else
  768. {
  769. pSaveData = new (std::nothrow) unsigned char[saveLen];
  770. memcpy(pSaveData, _data, saveLen);
  771. }
  772. for (int ind = 2; ind < saveLen; ind += bpp) {
  773. std::swap(pSaveData[ind - 2], pSaveData[ind]);
  774. }
  775. WICImageLoader img;
  776. bool bRet = img.encodeImageData(filePath, pSaveData, saveLen, targetFormat, _width, _height, containerFormat);
  777. delete[] pSaveData;
  778. return bRet;
  779. }
  780. #endif //CC_USE_WIC
  781. bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen)
  782. {
  783. #if CC_USE_WIC
  784. return decodeWithWIC(data, dataLen);
  785. #elif CC_USE_JPEG
  786. /* these are standard libjpeg structures for reading(decompression) */
  787. struct jpeg_decompress_struct cinfo;
  788. /* We use our private extension JPEG error handler.
  789. * Note that this struct must live as long as the main JPEG parameter
  790. * struct, to avoid dangling-pointer problems.
  791. */
  792. struct MyErrorMgr jerr;
  793. /* libjpeg data structure for storing one row, that is, scanline of an image */
  794. JSAMPROW row_pointer[1] = {0};
  795. unsigned long location = 0;
  796. bool ret = false;
  797. do
  798. {
  799. /* We set up the normal JPEG error routines, then override error_exit. */
  800. cinfo.err = jpeg_std_error(&jerr.pub);
  801. jerr.pub.error_exit = myErrorExit;
  802. /* Establish the setjmp return context for MyErrorExit to use. */
  803. if (setjmp(jerr.setjmp_buffer))
  804. {
  805. /* If we get here, the JPEG code has signaled an error.
  806. * We need to clean up the JPEG object, close the input file, and return.
  807. */
  808. jpeg_destroy_decompress(&cinfo);
  809. break;
  810. }
  811. /* setup decompression process and source, then read JPEG header */
  812. jpeg_create_decompress( &cinfo );
  813. #ifndef CC_TARGET_QT5
  814. jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), dataLen);
  815. #endif /* CC_TARGET_QT5 */
  816. /* reading the image header which contains image information */
  817. #if (JPEG_LIB_VERSION >= 90)
  818. // libjpeg 0.9 adds stricter types.
  819. jpeg_read_header(&cinfo, TRUE);
  820. #else
  821. jpeg_read_header(&cinfo, TRUE);
  822. #endif
  823. // we only support RGB or grayscale
  824. if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
  825. {
  826. _renderFormat = Texture2D::PixelFormat::I8;
  827. }else
  828. {
  829. cinfo.out_color_space = JCS_RGB;
  830. _renderFormat = Texture2D::PixelFormat::RGB888;
  831. }
  832. /* Start decompression jpeg here */
  833. jpeg_start_decompress( &cinfo );
  834. /* init image info */
  835. _width = cinfo.output_width;
  836. _height = cinfo.output_height;
  837. _dataLen = cinfo.output_width*cinfo.output_height*cinfo.output_components;
  838. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  839. CC_BREAK_IF(! _data);
  840. /* now actually read the jpeg into the raw buffer */
  841. /* read one scan line at a time */
  842. while (cinfo.output_scanline < cinfo.output_height)
  843. {
  844. row_pointer[0] = _data + location;
  845. location += cinfo.output_width*cinfo.output_components;
  846. jpeg_read_scanlines(&cinfo, row_pointer, 1);
  847. }
  848. /* When read image file with broken data, jpeg_finish_decompress() may cause error.
  849. * Besides, jpeg_destroy_decompress() shall deallocate and release all memory associated
  850. * with the decompression object.
  851. * So it doesn't need to call jpeg_finish_decompress().
  852. */
  853. //jpeg_finish_decompress( &cinfo );
  854. jpeg_destroy_decompress( &cinfo );
  855. /* wrap up decompression, destroy objects, free pointers and close open files */
  856. ret = true;
  857. } while (0);
  858. return ret;
  859. #else
  860. CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
  861. return false;
  862. #endif // CC_USE_JPEG
  863. }
  864. bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen)
  865. {
  866. #if CC_USE_WIC
  867. return decodeWithWIC(data, dataLen);
  868. #elif CC_USE_PNG
  869. // length of bytes to check if it is a valid png file
  870. #define PNGSIGSIZE 8
  871. bool ret = false;
  872. png_byte header[PNGSIGSIZE] = {0};
  873. png_structp png_ptr = 0;
  874. png_infop info_ptr = 0;
  875. do
  876. {
  877. // png header len is 8 bytes
  878. CC_BREAK_IF(dataLen < PNGSIGSIZE);
  879. // check the data is png or not
  880. memcpy(header, data, PNGSIGSIZE);
  881. CC_BREAK_IF(png_sig_cmp(header, 0, PNGSIGSIZE));
  882. // init png_struct
  883. png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
  884. CC_BREAK_IF(! png_ptr);
  885. // init png_info
  886. info_ptr = png_create_info_struct(png_ptr);
  887. CC_BREAK_IF(!info_ptr);
  888. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_TIZEN)
  889. CC_BREAK_IF(setjmp(png_jmpbuf(png_ptr)));
  890. #endif
  891. // set the read call back function
  892. tImageSource imageSource;
  893. imageSource.data = (unsigned char*)data;
  894. imageSource.size = dataLen;
  895. imageSource.offset = 0;
  896. png_set_read_fn(png_ptr, &imageSource, pngReadCallback);
  897. // read png header info
  898. // read png file info
  899. png_read_info(png_ptr, info_ptr);
  900. _width = png_get_image_width(png_ptr, info_ptr);
  901. _height = png_get_image_height(png_ptr, info_ptr);
  902. png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr);
  903. png_uint_32 color_type = png_get_color_type(png_ptr, info_ptr);
  904. //CCLOG("color type %u", color_type);
  905. // force palette images to be expanded to 24-bit RGB
  906. // it may include alpha channel
  907. if (color_type == PNG_COLOR_TYPE_PALETTE)
  908. {
  909. png_set_palette_to_rgb(png_ptr);
  910. }
  911. // low-bit-depth grayscale images are to be expanded to 8 bits
  912. if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
  913. {
  914. bit_depth = 8;
  915. png_set_expand_gray_1_2_4_to_8(png_ptr);
  916. }
  917. // expand any tRNS chunk data into a full alpha channel
  918. if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
  919. {
  920. png_set_tRNS_to_alpha(png_ptr);
  921. }
  922. // reduce images with 16-bit samples to 8 bits
  923. if (bit_depth == 16)
  924. {
  925. png_set_strip_16(png_ptr);
  926. }
  927. // Expanded earlier for grayscale, now take care of palette and rgb
  928. if (bit_depth < 8)
  929. {
  930. png_set_packing(png_ptr);
  931. }
  932. // update info
  933. png_read_update_info(png_ptr, info_ptr);
  934. color_type = png_get_color_type(png_ptr, info_ptr);
  935. switch (color_type)
  936. {
  937. case PNG_COLOR_TYPE_GRAY:
  938. _renderFormat = Texture2D::PixelFormat::I8;
  939. break;
  940. case PNG_COLOR_TYPE_GRAY_ALPHA:
  941. _renderFormat = Texture2D::PixelFormat::AI88;
  942. break;
  943. case PNG_COLOR_TYPE_RGB:
  944. _renderFormat = Texture2D::PixelFormat::RGB888;
  945. break;
  946. case PNG_COLOR_TYPE_RGB_ALPHA:
  947. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  948. break;
  949. default:
  950. break;
  951. }
  952. // read png data
  953. png_size_t rowbytes;
  954. png_bytep* row_pointers = (png_bytep*)malloc( sizeof(png_bytep) * _height );
  955. rowbytes = png_get_rowbytes(png_ptr, info_ptr);
  956. _dataLen = rowbytes * _height;
  957. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  958. if (!_data)
  959. {
  960. if (row_pointers != nullptr)
  961. {
  962. free(row_pointers);
  963. }
  964. break;
  965. }
  966. for (unsigned short i = 0; i < _height; ++i)
  967. {
  968. row_pointers[i] = _data + i*rowbytes;
  969. }
  970. png_read_image(png_ptr, row_pointers);
  971. png_read_end(png_ptr, nullptr);
  972. // premultiplied alpha for RGBA8888
  973. if (PNG_PREMULTIPLIED_ALPHA_ENABLED && color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  974. {
  975. premultipliedAlpha();
  976. }
  977. if (row_pointers != nullptr)
  978. {
  979. free(row_pointers);
  980. }
  981. ret = true;
  982. } while (0);
  983. if (png_ptr)
  984. {
  985. png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : 0, 0);
  986. }
  987. return ret;
  988. #else
  989. CCLOG("png is not enabled, please enable it in ccConfig.h");
  990. return false;
  991. #endif //CC_USE_PNG
  992. }
  993. #if CC_USE_TIFF
  994. namespace
  995. {
  996. static tmsize_t tiffReadProc(thandle_t fd, void* buf, tmsize_t size)
  997. {
  998. tImageSource* isource = (tImageSource*)fd;
  999. uint8* ma;
  1000. uint64 mb;
  1001. unsigned long n;
  1002. unsigned long o;
  1003. tmsize_t p;
  1004. ma=(uint8*)buf;
  1005. mb=size;
  1006. p=0;
  1007. while (mb>0)
  1008. {
  1009. n=0x80000000UL;
  1010. if ((uint64)n>mb)
  1011. n=(unsigned long)mb;
  1012. if ((int)(isource->offset + n) <= isource->size)
  1013. {
  1014. memcpy(ma, isource->data+isource->offset, n);
  1015. isource->offset += n;
  1016. o = n;
  1017. }
  1018. else
  1019. {
  1020. return 0;
  1021. }
  1022. ma+=o;
  1023. mb-=o;
  1024. p+=o;
  1025. if (o!=n)
  1026. {
  1027. break;
  1028. }
  1029. }
  1030. return p;
  1031. }
  1032. static tmsize_t tiffWriteProc(thandle_t /*fd*/, void* /*buf*/, tmsize_t /*size*/)
  1033. {
  1034. return 0;
  1035. }
  1036. static uint64 tiffSeekProc(thandle_t fd, uint64 off, int whence)
  1037. {
  1038. tImageSource* isource = (tImageSource*)fd;
  1039. uint64 ret = -1;
  1040. do
  1041. {
  1042. if (whence == SEEK_SET)
  1043. {
  1044. CC_BREAK_IF(off >= (uint64)isource->size);
  1045. ret = isource->offset = (uint32)off;
  1046. }
  1047. else if (whence == SEEK_CUR)
  1048. {
  1049. CC_BREAK_IF(isource->offset + off >= (uint64)isource->size);
  1050. ret = isource->offset += (uint32)off;
  1051. }
  1052. else if (whence == SEEK_END)
  1053. {
  1054. CC_BREAK_IF(off >= (uint64)isource->size);
  1055. ret = isource->offset = (uint32)(isource->size-1 - off);
  1056. }
  1057. else
  1058. {
  1059. CC_BREAK_IF(off >= (uint64)isource->size);
  1060. ret = isource->offset = (uint32)off;
  1061. }
  1062. } while (0);
  1063. return ret;
  1064. }
  1065. static uint64 tiffSizeProc(thandle_t fd)
  1066. {
  1067. tImageSource* imageSrc = (tImageSource*)fd;
  1068. return imageSrc->size;
  1069. }
  1070. static int tiffCloseProc(thandle_t /*fd*/)
  1071. {
  1072. return 0;
  1073. }
  1074. static int tiffMapProc(thandle_t /*fd*/, void** /*base*/, toff_t* /*size*/)
  1075. {
  1076. return 0;
  1077. }
  1078. static void tiffUnmapProc(thandle_t /*fd*/, void* /*base*/, toff_t /*size*/)
  1079. {
  1080. }
  1081. }
  1082. #endif // CC_USE_TIFF
  1083. bool Image::initWithTiffData(const unsigned char * data, ssize_t dataLen)
  1084. {
  1085. #if CC_USE_WIC
  1086. return decodeWithWIC(data, dataLen);
  1087. #elif CC_USE_TIFF
  1088. bool ret = false;
  1089. do
  1090. {
  1091. // set the read call back function
  1092. tImageSource imageSource;
  1093. imageSource.data = data;
  1094. imageSource.size = dataLen;
  1095. imageSource.offset = 0;
  1096. TIFF* tif = TIFFClientOpen("file.tif", "r", (thandle_t)&imageSource,
  1097. tiffReadProc, tiffWriteProc,
  1098. tiffSeekProc, tiffCloseProc, tiffSizeProc,
  1099. tiffMapProc,
  1100. tiffUnmapProc);
  1101. CC_BREAK_IF(nullptr == tif);
  1102. uint32 w = 0, h = 0;
  1103. uint16 bitsPerSample = 0, samplePerPixel = 0, planarConfig = 0;
  1104. size_t npixels = 0;
  1105. TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
  1106. TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
  1107. TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bitsPerSample);
  1108. TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samplePerPixel);
  1109. TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planarConfig);
  1110. npixels = w * h;
  1111. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1112. _width = w;
  1113. _height = h;
  1114. _dataLen = npixels * sizeof (uint32);
  1115. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1116. uint32* raster = (uint32*) _TIFFmalloc(npixels * sizeof (uint32));
  1117. if (raster != nullptr)
  1118. {
  1119. if (TIFFReadRGBAImageOriented(tif, w, h, raster, ORIENTATION_TOPLEFT, 0))
  1120. {
  1121. /* the raster data is pre-multiplied by the alpha component
  1122. after invoking TIFFReadRGBAImageOriented*/
  1123. _hasPremultipliedAlpha = true;
  1124. memcpy(_data, raster, npixels*sizeof (uint32));
  1125. }
  1126. _TIFFfree(raster);
  1127. }
  1128. TIFFClose(tif);
  1129. ret = true;
  1130. } while (0);
  1131. return ret;
  1132. #else
  1133. CCLOG("tiff is not enabled, please enable it in ccConfig.h");
  1134. return false;
  1135. #endif //CC_USE_TIFF
  1136. }
  1137. namespace
  1138. {
  1139. bool testFormatForPvr2TCSupport(PVR2TexturePixelFormat /*format*/)
  1140. {
  1141. return true;
  1142. }
  1143. bool testFormatForPvr3TCSupport(PVR3TexturePixelFormat format)
  1144. {
  1145. switch (format) {
  1146. case PVR3TexturePixelFormat::DXT1:
  1147. case PVR3TexturePixelFormat::DXT3:
  1148. case PVR3TexturePixelFormat::DXT5:
  1149. return Configuration::getInstance()->supportsS3TC();
  1150. case PVR3TexturePixelFormat::BGRA8888:
  1151. return Configuration::getInstance()->supportsBGRA8888();
  1152. case PVR3TexturePixelFormat::PVRTC2BPP_RGB:
  1153. case PVR3TexturePixelFormat::PVRTC2BPP_RGBA:
  1154. case PVR3TexturePixelFormat::PVRTC4BPP_RGB:
  1155. case PVR3TexturePixelFormat::PVRTC4BPP_RGBA:
  1156. case PVR3TexturePixelFormat::ETC1:
  1157. case PVR3TexturePixelFormat::RGBA8888:
  1158. case PVR3TexturePixelFormat::RGBA4444:
  1159. case PVR3TexturePixelFormat::RGBA5551:
  1160. case PVR3TexturePixelFormat::RGB565:
  1161. case PVR3TexturePixelFormat::RGB888:
  1162. case PVR3TexturePixelFormat::A8:
  1163. case PVR3TexturePixelFormat::L8:
  1164. case PVR3TexturePixelFormat::LA88:
  1165. return true;
  1166. default:
  1167. return false;
  1168. }
  1169. }
  1170. }
  1171. bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
  1172. {
  1173. int dataLength = 0, dataOffset = 0, dataSize = 0;
  1174. int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
  1175. int width = 0, height = 0;
  1176. //Cast first sizeof(PVRTexHeader) bytes of data stream as PVRTexHeader
  1177. const PVRv2TexHeader *header = static_cast<const PVRv2TexHeader *>(static_cast<const void*>(data));
  1178. //Make sure that tag is in correct formatting
  1179. if (memcmp(&header->pvrTag, gPVRTexIdentifier, strlen(gPVRTexIdentifier)) != 0)
  1180. {
  1181. return false;
  1182. }
  1183. Configuration *configuration = Configuration::getInstance();
  1184. //can not detect the premultiplied alpha from pvr file, use _PVRHaveAlphaPremultiplied instead.
  1185. _hasPremultipliedAlpha = _PVRHaveAlphaPremultiplied;
  1186. unsigned int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
  1187. PVR2TexturePixelFormat formatFlags = static_cast<PVR2TexturePixelFormat>(flags & PVR_TEXTURE_FLAG_TYPE_MASK);
  1188. bool flipped = (flags & (unsigned int)PVR2TextureFlag::VerticalFlip) ? true : false;
  1189. if (flipped)
  1190. {
  1191. CCLOG("cocos2d: WARNING: Image is flipped. Regenerate it using PVRTexTool");
  1192. }
  1193. if (! configuration->supportsNPOT() &&
  1194. (static_cast<int>(header->width) != ccNextPOT(header->width)
  1195. || static_cast<int>(header->height) != ccNextPOT(header->height)))
  1196. {
  1197. CCLOG("cocos2d: ERROR: Loading an NPOT texture (%dx%d) but is not supported on this device", header->width, header->height);
  1198. return false;
  1199. }
  1200. if (!testFormatForPvr2TCSupport(formatFlags))
  1201. {
  1202. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1203. return false;
  1204. }
  1205. if (v2_pixel_formathash.find(formatFlags) == v2_pixel_formathash.end())
  1206. {
  1207. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1208. return false;
  1209. }
  1210. auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v2_pixel_formathash.at(formatFlags)));
  1211. if (it == Texture2D::getPixelFormatInfoMap().end())
  1212. {
  1213. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%02X. Re-encode it with a OpenGL pixel format variant", (int)formatFlags);
  1214. return false;
  1215. }
  1216. _renderFormat = it->first;
  1217. int bpp = it->second.bpp;
  1218. //Reset num of mipmaps
  1219. _numberOfMipmaps = 0;
  1220. //Get size of mipmap
  1221. _width = width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
  1222. _height = height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
  1223. //Get ptr to where data starts..
  1224. dataLength = CC_SWAP_INT32_LITTLE_TO_HOST(header->dataLength);
  1225. //Move by size of header
  1226. _dataLen = dataLen - sizeof(PVRv2TexHeader);
  1227. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1228. memcpy(_data, (unsigned char*)data + sizeof(PVRv2TexHeader), _dataLen);
  1229. // Calculate the data size for each texture level and respect the minimum number of blocks
  1230. while (dataOffset < dataLength)
  1231. {
  1232. switch (formatFlags) {
  1233. case PVR2TexturePixelFormat::PVRTC2BPP_RGBA:
  1234. if (!Configuration::getInstance()->supportsPVRTC())
  1235. {
  1236. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1237. _unpack = true;
  1238. _mipmaps[_numberOfMipmaps].len = width*height*4;
  1239. _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4];
  1240. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, true);
  1241. bpp = 2;
  1242. }
  1243. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  1244. widthBlocks = width / 8;
  1245. heightBlocks = height / 4;
  1246. break;
  1247. case PVR2TexturePixelFormat::PVRTC4BPP_RGBA:
  1248. if (!Configuration::getInstance()->supportsPVRTC())
  1249. {
  1250. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1251. _unpack = true;
  1252. _mipmaps[_numberOfMipmaps].len = width*height*4;
  1253. _mipmaps[_numberOfMipmaps].address = new (std::nothrow) unsigned char[width*height*4];
  1254. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[_numberOfMipmaps].address, false);
  1255. bpp = 4;
  1256. }
  1257. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1258. widthBlocks = width / 4;
  1259. heightBlocks = height / 4;
  1260. break;
  1261. case PVR2TexturePixelFormat::BGRA8888:
  1262. if (Configuration::getInstance()->supportsBGRA8888() == false)
  1263. {
  1264. CCLOG("cocos2d: Image. BGRA8888 not supported on this device");
  1265. return false;
  1266. }
  1267. default:
  1268. blockSize = 1;
  1269. widthBlocks = width;
  1270. heightBlocks = height;
  1271. break;
  1272. }
  1273. // Clamp to minimum number of blocks
  1274. if (widthBlocks < 2)
  1275. {
  1276. widthBlocks = 2;
  1277. }
  1278. if (heightBlocks < 2)
  1279. {
  1280. heightBlocks = 2;
  1281. }
  1282. dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
  1283. int packetLength = (dataLength - dataOffset);
  1284. packetLength = packetLength > dataSize ? dataSize : packetLength;
  1285. //Make record to the mipmaps array and increment counter
  1286. if(!_unpack)
  1287. {
  1288. _mipmaps[_numberOfMipmaps].address = _data + dataOffset;
  1289. _mipmaps[_numberOfMipmaps].len = packetLength;
  1290. }
  1291. _numberOfMipmaps++;
  1292. dataOffset += packetLength;
  1293. //Update width and height to the next lower power of two
  1294. width = MAX(width >> 1, 1);
  1295. height = MAX(height >> 1, 1);
  1296. }
  1297. if(_unpack)
  1298. {
  1299. _data = _mipmaps[0].address;
  1300. _dataLen = _mipmaps[0].len;
  1301. }
  1302. return true;
  1303. }
  1304. bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen)
  1305. {
  1306. if (static_cast<size_t>(dataLen) < sizeof(PVRv3TexHeader))
  1307. {
  1308. return false;
  1309. }
  1310. const PVRv3TexHeader *header = static_cast<const PVRv3TexHeader *>(static_cast<const void*>(data));
  1311. // validate version
  1312. if (CC_SWAP_INT32_BIG_TO_HOST(header->version) != 0x50565203)
  1313. {
  1314. CCLOG("cocos2d: WARNING: pvr file version mismatch");
  1315. return false;
  1316. }
  1317. // parse pixel format
  1318. PVR3TexturePixelFormat pixelFormat = static_cast<PVR3TexturePixelFormat>(header->pixelFormat);
  1319. if (!testFormatForPvr3TCSupport(pixelFormat))
  1320. {
  1321. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1322. static_cast<unsigned long long>(pixelFormat));
  1323. return false;
  1324. }
  1325. if (v3_pixel_formathash.find(pixelFormat) == v3_pixel_formathash.end())
  1326. {
  1327. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1328. static_cast<unsigned long long>(pixelFormat));
  1329. return false;
  1330. }
  1331. auto it = Texture2D::getPixelFormatInfoMap().find(getDevicePixelFormat(v3_pixel_formathash.at(pixelFormat)));
  1332. if (it == Texture2D::getPixelFormatInfoMap().end())
  1333. {
  1334. CCLOG("cocos2d: WARNING: Unsupported PVR Pixel Format: 0x%016llX. Re-encode it with a OpenGL pixel format variant",
  1335. static_cast<unsigned long long>(pixelFormat));
  1336. return false;
  1337. }
  1338. _renderFormat = it->first;
  1339. int bpp = it->second.bpp;
  1340. // flags
  1341. int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
  1342. // PVRv3 specifies premultiply alpha in a flag -- should always respect this in PVRv3 files
  1343. if (flags & (unsigned int)PVR3TextureFlag::PremultipliedAlpha)
  1344. {
  1345. _hasPremultipliedAlpha = true;
  1346. }
  1347. // sizing
  1348. int width = CC_SWAP_INT32_LITTLE_TO_HOST(header->width);
  1349. int height = CC_SWAP_INT32_LITTLE_TO_HOST(header->height);
  1350. _width = width;
  1351. _height = height;
  1352. int dataOffset = 0, dataSize = 0;
  1353. int blockSize = 0, widthBlocks = 0, heightBlocks = 0;
  1354. _dataLen = dataLen - (sizeof(PVRv3TexHeader) + header->metadataLength);
  1355. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1356. memcpy(_data, static_cast<const unsigned char*>(data) + sizeof(PVRv3TexHeader) + header->metadataLength, _dataLen);
  1357. _numberOfMipmaps = header->numberOfMipmaps;
  1358. CCASSERT(_numberOfMipmaps < MIPMAP_MAX, "Image: Maximum number of mimpaps reached. Increase the CC_MIPMAP_MAX value");
  1359. for (int i = 0; i < _numberOfMipmaps; i++)
  1360. {
  1361. switch ((PVR3TexturePixelFormat)pixelFormat)
  1362. {
  1363. case PVR3TexturePixelFormat::PVRTC2BPP_RGB :
  1364. case PVR3TexturePixelFormat::PVRTC2BPP_RGBA :
  1365. if (!Configuration::getInstance()->supportsPVRTC())
  1366. {
  1367. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1368. _unpack = true;
  1369. _mipmaps[i].len = width*height*4;
  1370. _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4];
  1371. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, true);
  1372. bpp = 2;
  1373. }
  1374. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  1375. widthBlocks = width / 8;
  1376. heightBlocks = height / 4;
  1377. break;
  1378. case PVR3TexturePixelFormat::PVRTC4BPP_RGB :
  1379. case PVR3TexturePixelFormat::PVRTC4BPP_RGBA :
  1380. if (!Configuration::getInstance()->supportsPVRTC())
  1381. {
  1382. CCLOG("cocos2d: Hardware PVR decoder not present. Using software decoder");
  1383. _unpack = true;
  1384. _mipmaps[i].len = width*height*4;
  1385. _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*4];
  1386. PVRTDecompressPVRTC(_data+dataOffset,width,height,_mipmaps[i].address, false);
  1387. bpp = 4;
  1388. }
  1389. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1390. widthBlocks = width / 4;
  1391. heightBlocks = height / 4;
  1392. break;
  1393. case PVR3TexturePixelFormat::ETC1:
  1394. if (!Configuration::getInstance()->supportsETC())
  1395. {
  1396. CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder");
  1397. int bytePerPixel = 3;
  1398. unsigned int stride = width * bytePerPixel;
  1399. _unpack = true;
  1400. _mipmaps[i].len = width*height*bytePerPixel;
  1401. _mipmaps[i].address = new (std::nothrow) unsigned char[width*height*bytePerPixel];
  1402. if (etc1_decode_image(static_cast<const unsigned char*>(_data+dataOffset), static_cast<etc1_byte*>(_mipmaps[i].address), width, height, bytePerPixel, stride) != 0)
  1403. {
  1404. return false;
  1405. }
  1406. }
  1407. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  1408. widthBlocks = width / 4;
  1409. heightBlocks = height / 4;
  1410. break;
  1411. case PVR3TexturePixelFormat::BGRA8888:
  1412. if (! Configuration::getInstance()->supportsBGRA8888())
  1413. {
  1414. CCLOG("cocos2d: Image. BGRA8888 not supported on this device");
  1415. return false;
  1416. }
  1417. default:
  1418. blockSize = 1;
  1419. widthBlocks = width;
  1420. heightBlocks = height;
  1421. break;
  1422. }
  1423. // Clamp to minimum number of blocks
  1424. if (widthBlocks < 2)
  1425. {
  1426. widthBlocks = 2;
  1427. }
  1428. if (heightBlocks < 2)
  1429. {
  1430. heightBlocks = 2;
  1431. }
  1432. dataSize = widthBlocks * heightBlocks * ((blockSize * bpp) / 8);
  1433. auto packetLength = _dataLen - dataOffset;
  1434. packetLength = packetLength > dataSize ? dataSize : packetLength;
  1435. if(!_unpack)
  1436. {
  1437. _mipmaps[i].address = _data + dataOffset;
  1438. _mipmaps[i].len = static_cast<int>(packetLength);
  1439. }
  1440. dataOffset += packetLength;
  1441. CCASSERT(dataOffset <= _dataLen, "Image: Invalid length");
  1442. width = MAX(width >> 1, 1);
  1443. height = MAX(height >> 1, 1);
  1444. }
  1445. if (_unpack)
  1446. {
  1447. _data = _mipmaps[0].address;
  1448. _dataLen = _mipmaps[0].len;
  1449. }
  1450. return true;
  1451. }
  1452. bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen)
  1453. {
  1454. const etc1_byte* header = static_cast<const etc1_byte*>(data);
  1455. //check the data
  1456. if (! etc1_pkm_is_valid(header))
  1457. {
  1458. return false;
  1459. }
  1460. _width = etc1_pkm_get_width(header);
  1461. _height = etc1_pkm_get_height(header);
  1462. if (0 == _width || 0 == _height)
  1463. {
  1464. return false;
  1465. }
  1466. if (Configuration::getInstance()->supportsETC())
  1467. {
  1468. //old opengl version has no define for GL_ETC1_RGB8_OES, add macro to make compiler happy.
  1469. #ifdef GL_ETC1_RGB8_OES
  1470. _renderFormat = Texture2D::PixelFormat::ETC;
  1471. _dataLen = dataLen - ETC_PKM_HEADER_SIZE;
  1472. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1473. memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen);
  1474. return true;
  1475. #else
  1476. CC_UNUSED_PARAM(dataLen);
  1477. #endif
  1478. }
  1479. else
  1480. {
  1481. CCLOG("cocos2d: Hardware ETC1 decoder not present. Using software decoder");
  1482. //if it is not gles or device do not support ETC, decode texture by software
  1483. int bytePerPixel = 3;
  1484. unsigned int stride = _width * bytePerPixel;
  1485. _renderFormat = Texture2D::PixelFormat::RGB888;
  1486. _dataLen = _width * _height * bytePerPixel;
  1487. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1488. if (etc1_decode_image(static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, static_cast<etc1_byte*>(_data), _width, _height, bytePerPixel, stride) != 0)
  1489. {
  1490. _dataLen = 0;
  1491. if (_data != nullptr)
  1492. {
  1493. free(_data);
  1494. }
  1495. return false;
  1496. }
  1497. return true;
  1498. }
  1499. return false;
  1500. }
  1501. bool Image::initWithTGAData(tImageTGA* tgaData)
  1502. {
  1503. bool ret = false;
  1504. do
  1505. {
  1506. CC_BREAK_IF(tgaData == nullptr);
  1507. // tgaLoadBuffer only support type 2, 3, 10
  1508. if (2 == tgaData->type || 10 == tgaData->type)
  1509. {
  1510. // true color
  1511. // unsupported RGB555
  1512. if (tgaData->pixelDepth == 16)
  1513. {
  1514. _renderFormat = Texture2D::PixelFormat::RGB5A1;
  1515. }
  1516. else if(tgaData->pixelDepth == 24)
  1517. {
  1518. _renderFormat = Texture2D::PixelFormat::RGB888;
  1519. }
  1520. else if(tgaData->pixelDepth == 32)
  1521. {
  1522. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1523. }
  1524. else
  1525. {
  1526. CCLOG("Image WARNING: unsupported true color tga data pixel format. FILE: %s", _filePath.c_str());
  1527. break;
  1528. }
  1529. }
  1530. else if(3 == tgaData->type)
  1531. {
  1532. // gray
  1533. if (8 == tgaData->pixelDepth)
  1534. {
  1535. _renderFormat = Texture2D::PixelFormat::I8;
  1536. }
  1537. else
  1538. {
  1539. // actually this won't happen, if it happens, maybe the image file is not a tga
  1540. CCLOG("Image WARNING: unsupported gray tga data pixel format. FILE: %s", _filePath.c_str());
  1541. break;
  1542. }
  1543. }
  1544. _width = tgaData->width;
  1545. _height = tgaData->height;
  1546. _data = tgaData->imageData;
  1547. _dataLen = _width * _height * tgaData->pixelDepth / 8;
  1548. _fileType = Format::TGA;
  1549. ret = true;
  1550. }while(false);
  1551. if (ret)
  1552. {
  1553. if (FileUtils::getInstance()->getFileExtension(_filePath) != ".tga")
  1554. {
  1555. CCLOG("Image WARNING: the image file suffix is not tga, but parsed as a tga image file. FILE: %s", _filePath.c_str());
  1556. }
  1557. }
  1558. else
  1559. {
  1560. if (tgaData && tgaData->imageData != nullptr)
  1561. {
  1562. free(tgaData->imageData);
  1563. _data = nullptr;
  1564. }
  1565. }
  1566. return ret;
  1567. }
  1568. namespace
  1569. {
  1570. static uint32_t makeFourCC(char ch0, char ch1, char ch2, char ch3)
  1571. {
  1572. const uint32_t fourCC = ((uint32_t)(char)(ch0) | ((uint32_t)(char)(ch1) << 8) | ((uint32_t)(char)(ch2) << 16) | ((uint32_t)(char)(ch3) << 24 ));
  1573. return fourCC;
  1574. }
  1575. }
  1576. bool Image::initWithS3TCData(const unsigned char * data, ssize_t dataLen)
  1577. {
  1578. const uint32_t FOURCC_DXT1 = makeFourCC('D', 'X', 'T', '1');
  1579. const uint32_t FOURCC_DXT3 = makeFourCC('D', 'X', 'T', '3');
  1580. const uint32_t FOURCC_DXT5 = makeFourCC('D', 'X', 'T', '5');
  1581. /* load the .dds file */
  1582. S3TCTexHeader *header = (S3TCTexHeader *)data;
  1583. unsigned char *pixelData = static_cast<unsigned char*>(malloc((dataLen - sizeof(S3TCTexHeader)) * sizeof(unsigned char)));
  1584. memcpy((void *)pixelData, data + sizeof(S3TCTexHeader), dataLen - sizeof(S3TCTexHeader));
  1585. _width = header->ddsd.width;
  1586. _height = header->ddsd.height;
  1587. _numberOfMipmaps = MAX(1, header->ddsd.DUMMYUNIONNAMEN2.mipMapCount); //if dds header reports 0 mipmaps, set to 1 to force correct software decoding (if needed).
  1588. _dataLen = 0;
  1589. int blockSize = (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC) ? 8 : 16;
  1590. /* calculate the dataLen */
  1591. int width = _width;
  1592. int height = _height;
  1593. if (Configuration::getInstance()->supportsS3TC()) //compressed data length
  1594. {
  1595. _dataLen = dataLen - sizeof(S3TCTexHeader);
  1596. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1597. memcpy((void *)_data,(void *)pixelData , _dataLen);
  1598. }
  1599. else //decompressed data length
  1600. {
  1601. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1602. {
  1603. if (width == 0) width = 1;
  1604. if (height == 0) height = 1;
  1605. _dataLen += (height * width *4);
  1606. width >>= 1;
  1607. height >>= 1;
  1608. }
  1609. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1610. }
  1611. /* if hardware supports s3tc, set pixelformat before loading mipmaps, to support non-mipmapped textures */
  1612. if (Configuration::getInstance()->supportsS3TC())
  1613. { //decode texture through hardware
  1614. if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1615. {
  1616. _renderFormat = Texture2D::PixelFormat::S3TC_DXT1;
  1617. }
  1618. else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1619. {
  1620. _renderFormat = Texture2D::PixelFormat::S3TC_DXT3;
  1621. }
  1622. else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1623. {
  1624. _renderFormat = Texture2D::PixelFormat::S3TC_DXT5;
  1625. }
  1626. } else { //will software decode
  1627. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1628. }
  1629. /* load the mipmaps */
  1630. int encodeOffset = 0;
  1631. int decodeOffset = 0;
  1632. width = _width; height = _height;
  1633. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1634. {
  1635. if (width == 0) width = 1;
  1636. if (height == 0) height = 1;
  1637. int size = ((width+3)/4)*((height+3)/4)*blockSize;
  1638. if (Configuration::getInstance()->supportsS3TC())
  1639. { //decode texture through hardware
  1640. _mipmaps[i].address = (unsigned char *)_data + encodeOffset;
  1641. _mipmaps[i].len = size;
  1642. }
  1643. else
  1644. { //if it is not gles or device do not support S3TC, decode texture by software
  1645. CCLOG("cocos2d: Hardware S3TC decoder not present. Using software decoder");
  1646. int bytePerPixel = 4;
  1647. unsigned int stride = width * bytePerPixel;
  1648. std::vector<unsigned char> decodeImageData(stride * height);
  1649. if (FOURCC_DXT1 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1650. {
  1651. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT1);
  1652. }
  1653. else if (FOURCC_DXT3 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1654. {
  1655. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT3);
  1656. }
  1657. else if (FOURCC_DXT5 == header->ddsd.DUMMYUNIONNAMEN4.ddpfPixelFormat.fourCC)
  1658. {
  1659. s3tc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, S3TCDecodeFlag::DXT5);
  1660. }
  1661. _mipmaps[i].address = (unsigned char *)_data + decodeOffset;
  1662. _mipmaps[i].len = (stride * height);
  1663. memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len);
  1664. decodeOffset += stride * height;
  1665. }
  1666. encodeOffset += size;
  1667. width >>= 1;
  1668. height >>= 1;
  1669. }
  1670. /* end load the mipmaps */
  1671. if (pixelData != nullptr)
  1672. {
  1673. free(pixelData);
  1674. };
  1675. return true;
  1676. }
  1677. bool Image::initWithATITCData(const unsigned char *data, ssize_t dataLen)
  1678. {
  1679. /* load the .ktx file */
  1680. ATITCTexHeader *header = (ATITCTexHeader *)data;
  1681. _width = header->pixelWidth;
  1682. _height = header->pixelHeight;
  1683. _numberOfMipmaps = header->numberOfMipmapLevels;
  1684. int blockSize = 0;
  1685. switch (header->glInternalFormat)
  1686. {
  1687. case CC_GL_ATC_RGB_AMD:
  1688. blockSize = 8;
  1689. break;
  1690. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1691. blockSize = 16;
  1692. break;
  1693. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1694. blockSize = 16;
  1695. break;
  1696. default:
  1697. break;
  1698. }
  1699. /* pixelData point to the compressed data address */
  1700. unsigned char *pixelData = (unsigned char *)data + sizeof(ATITCTexHeader) + header->bytesOfKeyValueData + 4;
  1701. /* calculate the dataLen */
  1702. int width = _width;
  1703. int height = _height;
  1704. if (Configuration::getInstance()->supportsATITC()) //compressed data length
  1705. {
  1706. _dataLen = dataLen - sizeof(ATITCTexHeader) - header->bytesOfKeyValueData - 4;
  1707. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1708. memcpy((void *)_data,(void *)pixelData , _dataLen);
  1709. }
  1710. else //decompressed data length
  1711. {
  1712. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1713. {
  1714. if (width == 0) width = 1;
  1715. if (height == 0) height = 1;
  1716. _dataLen += (height * width *4);
  1717. width >>= 1;
  1718. height >>= 1;
  1719. }
  1720. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1721. }
  1722. /* load the mipmaps */
  1723. int encodeOffset = 0;
  1724. int decodeOffset = 0;
  1725. width = _width; height = _height;
  1726. for (int i = 0; i < _numberOfMipmaps && (width || height); ++i)
  1727. {
  1728. if (width == 0) width = 1;
  1729. if (height == 0) height = 1;
  1730. int size = ((width+3)/4)*((height+3)/4)*blockSize;
  1731. if (Configuration::getInstance()->supportsATITC())
  1732. {
  1733. /* decode texture through hardware */
  1734. CCLOG("this is atitc H decode");
  1735. switch (header->glInternalFormat)
  1736. {
  1737. case CC_GL_ATC_RGB_AMD:
  1738. _renderFormat = Texture2D::PixelFormat::ATC_RGB;
  1739. break;
  1740. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1741. _renderFormat = Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA;
  1742. break;
  1743. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1744. _renderFormat = Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA;
  1745. break;
  1746. default:
  1747. break;
  1748. }
  1749. _mipmaps[i].address = (unsigned char *)_data + encodeOffset;
  1750. _mipmaps[i].len = size;
  1751. }
  1752. else
  1753. {
  1754. /* if it is not gles or device do not support ATITC, decode texture by software */
  1755. CCLOG("cocos2d: Hardware ATITC decoder not present. Using software decoder");
  1756. int bytePerPixel = 4;
  1757. unsigned int stride = width * bytePerPixel;
  1758. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1759. std::vector<unsigned char> decodeImageData(stride * height);
  1760. switch (header->glInternalFormat)
  1761. {
  1762. case CC_GL_ATC_RGB_AMD:
  1763. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_RGB);
  1764. break;
  1765. case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
  1766. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA);
  1767. break;
  1768. case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
  1769. atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA);
  1770. break;
  1771. default:
  1772. break;
  1773. }
  1774. _mipmaps[i].address = (unsigned char *)_data + decodeOffset;
  1775. _mipmaps[i].len = (stride * height);
  1776. memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len);
  1777. decodeOffset += stride * height;
  1778. }
  1779. encodeOffset += (size + 4);
  1780. width >>= 1;
  1781. height >>= 1;
  1782. }
  1783. /* end load the mipmaps */
  1784. return true;
  1785. }
  1786. bool Image::initWithPVRData(const unsigned char * data, ssize_t dataLen)
  1787. {
  1788. return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen);
  1789. }
  1790. bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen)
  1791. {
  1792. #if CC_USE_WEBP
  1793. bool ret = false;
  1794. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1795. CCLOG("WEBP image format not supported on WinRT or WP8");
  1796. #else
  1797. do
  1798. {
  1799. WebPDecoderConfig config;
  1800. if (WebPInitDecoderConfig(&config) == 0) break;
  1801. if (WebPGetFeatures(static_cast<const uint8_t*>(data), dataLen, &config.input) != VP8_STATUS_OK) break;
  1802. if (config.input.width == 0 || config.input.height == 0) break;
  1803. config.output.colorspace = config.input.has_alpha?MODE_rgbA:MODE_RGB;
  1804. _renderFormat = config.input.has_alpha?Texture2D::PixelFormat::RGBA8888:Texture2D::PixelFormat::RGB888;
  1805. _width = config.input.width;
  1806. _height = config.input.height;
  1807. //we ask webp to give data with premultiplied alpha
  1808. _hasPremultipliedAlpha = (config.input.has_alpha != 0);
  1809. _dataLen = _width * _height * (config.input.has_alpha?4:3);
  1810. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1811. config.output.u.RGBA.rgba = static_cast<uint8_t*>(_data);
  1812. config.output.u.RGBA.stride = _width * (config.input.has_alpha?4:3);
  1813. config.output.u.RGBA.size = _dataLen;
  1814. config.output.is_external_memory = 1;
  1815. if (WebPDecode(static_cast<const uint8_t*>(data), dataLen, &config) != VP8_STATUS_OK)
  1816. {
  1817. free(_data);
  1818. _data = nullptr;
  1819. break;
  1820. }
  1821. ret = true;
  1822. } while (0);
  1823. #endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
  1824. return ret;
  1825. #else
  1826. CCLOG("webp is not enabled, please enable it in ccConfig.h");
  1827. return false;
  1828. #endif // CC_USE_WEBP
  1829. }
  1830. bool Image::initWithRawData(const unsigned char * data, ssize_t /*dataLen*/, int width, int height, int /*bitsPerComponent*/, bool preMulti)
  1831. {
  1832. bool ret = false;
  1833. do
  1834. {
  1835. CC_BREAK_IF(0 == width || 0 == height);
  1836. _height = height;
  1837. _width = width;
  1838. _hasPremultipliedAlpha = preMulti;
  1839. _renderFormat = Texture2D::PixelFormat::RGBA8888;
  1840. // only RGBA8888 supported
  1841. int bytesPerComponent = 4;
  1842. _dataLen = height * width * bytesPerComponent;
  1843. _data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
  1844. CC_BREAK_IF(! _data);
  1845. memcpy(_data, data, _dataLen);
  1846. ret = true;
  1847. } while (0);
  1848. return ret;
  1849. }
  1850. #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
  1851. bool Image::saveToFile(const std::string& filename, bool isToRGB)
  1852. {
  1853. //only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data
  1854. if (isCompressed() || (_renderFormat != Texture2D::PixelFormat::RGB888 && _renderFormat != Texture2D::PixelFormat::RGBA8888))
  1855. {
  1856. CCLOG("cocos2d: Image: saveToFile is only support for Texture2D::PixelFormat::RGB888 or Texture2D::PixelFormat::RGBA8888 uncompressed data for now");
  1857. return false;
  1858. }
  1859. std::string fileExtension = FileUtils::getInstance()->getFileExtension(filename);
  1860. if (fileExtension == ".png")
  1861. {
  1862. return saveImageToPNG(filename, isToRGB);
  1863. }
  1864. else if (fileExtension == ".jpg")
  1865. {
  1866. return saveImageToJPG(filename);
  1867. }
  1868. else
  1869. {
  1870. CCLOG("cocos2d: Image: saveToFile no support file extension(only .png or .jpg) for file: %s", filename.c_str());
  1871. return false;
  1872. }
  1873. }
  1874. #endif
  1875. bool Image::saveImageToPNG(const std::string& filePath, bool isToRGB)
  1876. {
  1877. #if CC_USE_WIC
  1878. return encodeWithWIC(filePath, isToRGB, GUID_ContainerFormatPng);
  1879. #elif CC_USE_PNG
  1880. bool ret = false;
  1881. do
  1882. {
  1883. FILE *fp;
  1884. png_structp png_ptr;
  1885. png_infop info_ptr;
  1886. png_colorp palette;
  1887. png_bytep *row_pointers;
  1888. fp = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb");
  1889. CC_BREAK_IF(nullptr == fp);
  1890. png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  1891. if (nullptr == png_ptr)
  1892. {
  1893. fclose(fp);
  1894. break;
  1895. }
  1896. info_ptr = png_create_info_struct(png_ptr);
  1897. if (nullptr == info_ptr)
  1898. {
  1899. fclose(fp);
  1900. png_destroy_write_struct(&png_ptr, nullptr);
  1901. break;
  1902. }
  1903. #if (CC_TARGET_PLATFORM != CC_PLATFORM_BADA && CC_TARGET_PLATFORM != CC_PLATFORM_NACL && CC_TARGET_PLATFORM != CC_PLATFORM_TIZEN)
  1904. if (setjmp(png_jmpbuf(png_ptr)))
  1905. {
  1906. fclose(fp);
  1907. png_destroy_write_struct(&png_ptr, &info_ptr);
  1908. break;
  1909. }
  1910. #endif
  1911. png_init_io(png_ptr, fp);
  1912. if (!isToRGB && hasAlpha())
  1913. {
  1914. png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB_ALPHA,
  1915. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1916. }
  1917. else
  1918. {
  1919. png_set_IHDR(png_ptr, info_ptr, _width, _height, 8, PNG_COLOR_TYPE_RGB,
  1920. PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
  1921. }
  1922. palette = (png_colorp)png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH * sizeof (png_color));
  1923. png_set_PLTE(png_ptr, info_ptr, palette, PNG_MAX_PALETTE_LENGTH);
  1924. png_write_info(png_ptr, info_ptr);
  1925. png_set_packing(png_ptr);
  1926. row_pointers = (png_bytep *)malloc(_height * sizeof(png_bytep));
  1927. if(row_pointers == nullptr)
  1928. {
  1929. fclose(fp);
  1930. png_destroy_write_struct(&png_ptr, &info_ptr);
  1931. break;
  1932. }
  1933. if (!hasAlpha())
  1934. {
  1935. for (int i = 0; i < (int)_height; i++)
  1936. {
  1937. row_pointers[i] = (png_bytep)_data + i * _width * 3;
  1938. }
  1939. png_write_image(png_ptr, row_pointers);
  1940. free(row_pointers);
  1941. row_pointers = nullptr;
  1942. }
  1943. else
  1944. {
  1945. if (isToRGB)
  1946. {
  1947. unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
  1948. if (nullptr == tempData)
  1949. {
  1950. fclose(fp);
  1951. png_destroy_write_struct(&png_ptr, &info_ptr);
  1952. free(row_pointers);
  1953. row_pointers = nullptr;
  1954. break;
  1955. }
  1956. for (int i = 0; i < _height; ++i)
  1957. {
  1958. for (int j = 0; j < _width; ++j)
  1959. {
  1960. tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
  1961. tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
  1962. tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
  1963. }
  1964. }
  1965. for (int i = 0; i < (int)_height; i++)
  1966. {
  1967. row_pointers[i] = (png_bytep)tempData + i * _width * 3;
  1968. }
  1969. png_write_image(png_ptr, row_pointers);
  1970. free(row_pointers);
  1971. row_pointers = nullptr;
  1972. if (tempData != nullptr)
  1973. {
  1974. free(tempData);
  1975. }
  1976. }
  1977. else
  1978. {
  1979. for (int i = 0; i < (int)_height; i++)
  1980. {
  1981. row_pointers[i] = (png_bytep)_data + i * _width * 4;
  1982. }
  1983. png_write_image(png_ptr, row_pointers);
  1984. free(row_pointers);
  1985. row_pointers = nullptr;
  1986. }
  1987. }
  1988. png_write_end(png_ptr, info_ptr);
  1989. png_free(png_ptr, palette);
  1990. palette = nullptr;
  1991. png_destroy_write_struct(&png_ptr, &info_ptr);
  1992. fclose(fp);
  1993. ret = true;
  1994. } while (0);
  1995. return ret;
  1996. #else
  1997. CCLOG("png is not enabled, please enable it in ccConfig.h");
  1998. return false;
  1999. #endif // CC_USE_PNG
  2000. }
  2001. bool Image::saveImageToJPG(const std::string& filePath)
  2002. {
  2003. #if CC_USE_WIC
  2004. return encodeWithWIC(filePath, false, GUID_ContainerFormatJpeg);
  2005. #elif CC_USE_JPEG
  2006. bool ret = false;
  2007. do
  2008. {
  2009. struct jpeg_compress_struct cinfo;
  2010. struct jpeg_error_mgr jerr;
  2011. FILE * outfile; /* target file */
  2012. JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
  2013. int row_stride; /* physical row width in image buffer */
  2014. cinfo.err = jpeg_std_error(&jerr);
  2015. /* Now we can initialize the JPEG compression object. */
  2016. jpeg_create_compress(&cinfo);
  2017. CC_BREAK_IF((outfile = fopen(FileUtils::getInstance()->getSuitableFOpen(filePath).c_str(), "wb")) == nullptr);
  2018. jpeg_stdio_dest(&cinfo, outfile);
  2019. cinfo.image_width = _width; /* image width and height, in pixels */
  2020. cinfo.image_height = _height;
  2021. cinfo.input_components = 3; /* # of color components per pixel */
  2022. cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
  2023. jpeg_set_defaults(&cinfo);
  2024. jpeg_set_quality(&cinfo, 90, TRUE);
  2025. jpeg_start_compress(&cinfo, TRUE);
  2026. row_stride = _width * 3; /* JSAMPLEs per row in image_buffer */
  2027. if (hasAlpha())
  2028. {
  2029. unsigned char *tempData = static_cast<unsigned char*>(malloc(_width * _height * 3 * sizeof(unsigned char)));
  2030. if (nullptr == tempData)
  2031. {
  2032. jpeg_finish_compress(&cinfo);
  2033. jpeg_destroy_compress(&cinfo);
  2034. fclose(outfile);
  2035. break;
  2036. }
  2037. for (int i = 0; i < _height; ++i)
  2038. {
  2039. for (int j = 0; j < _width; ++j)
  2040. {
  2041. tempData[(i * _width + j) * 3] = _data[(i * _width + j) * 4];
  2042. tempData[(i * _width + j) * 3 + 1] = _data[(i * _width + j) * 4 + 1];
  2043. tempData[(i * _width + j) * 3 + 2] = _data[(i * _width + j) * 4 + 2];
  2044. }
  2045. }
  2046. while (cinfo.next_scanline < cinfo.image_height)
  2047. {
  2048. row_pointer[0] = & tempData[cinfo.next_scanline * row_stride];
  2049. (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  2050. }
  2051. if (tempData != nullptr)
  2052. {
  2053. free(tempData);
  2054. }
  2055. }
  2056. else
  2057. {
  2058. while (cinfo.next_scanline < cinfo.image_height) {
  2059. row_pointer[0] = & _data[cinfo.next_scanline * row_stride];
  2060. (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
  2061. }
  2062. }
  2063. jpeg_finish_compress(&cinfo);
  2064. fclose(outfile);
  2065. jpeg_destroy_compress(&cinfo);
  2066. ret = true;
  2067. } while (0);
  2068. return ret;
  2069. #else
  2070. CCLOG("jpeg is not enabled, please enable it in ccConfig.h");
  2071. return false;
  2072. #endif // CC_USE_JPEG
  2073. }
  2074. void Image::premultipliedAlpha()
  2075. {
  2076. #if CC_ENABLE_PREMULTIPLIED_ALPHA == 0
  2077. _hasPremultipliedAlpha = false;
  2078. return;
  2079. #else
  2080. CCASSERT(_renderFormat == Texture2D::PixelFormat::RGBA8888, "The pixel format should be RGBA8888!");
  2081. unsigned int* fourBytes = (unsigned int*)_data;
  2082. for(int i = 0; i < _width * _height; i++)
  2083. {
  2084. unsigned char* p = _data + i * 4;
  2085. fourBytes[i] = CC_RGB_PREMULTIPLY_ALPHA(p[0], p[1], p[2], p[3]);
  2086. }
  2087. _hasPremultipliedAlpha = true;
  2088. #endif
  2089. }
  2090. void Image::setPVRImagesHavePremultipliedAlpha(bool haveAlphaPremultiplied)
  2091. {
  2092. _PVRHaveAlphaPremultiplied = haveAlphaPremultiplied;
  2093. }
  2094. NS_CC_END