CCImage.cpp 68 KB

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