EXRLoader.js 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  1. import {
  2. DataTextureLoader,
  3. DataUtils,
  4. FloatType,
  5. HalfFloatType,
  6. NoColorSpace,
  7. LinearFilter,
  8. LinearSRGBColorSpace,
  9. RedFormat,
  10. RGBAFormat
  11. } from 'three';
  12. import * as fflate from '../libs/fflate.module.js';
  13. // Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita
  14. // implementation, so I have preserved their copyright notices.
  15. // /*
  16. // Copyright (c) 2014 - 2017, Syoyo Fujita
  17. // All rights reserved.
  18. // Redistribution and use in source and binary forms, with or without
  19. // modification, are permitted provided that the following conditions are met:
  20. // * Redistributions of source code must retain the above copyright
  21. // notice, this list of conditions and the following disclaimer.
  22. // * Redistributions in binary form must reproduce the above copyright
  23. // notice, this list of conditions and the following disclaimer in the
  24. // documentation and/or other materials provided with the distribution.
  25. // * Neither the name of the Syoyo Fujita nor the
  26. // names of its contributors may be used to endorse or promote products
  27. // derived from this software without specific prior written permission.
  28. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  29. // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  30. // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  32. // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  33. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  34. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  35. // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  36. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  37. // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. // */
  39. // // TinyEXR contains some OpenEXR code, which is licensed under ------------
  40. // ///////////////////////////////////////////////////////////////////////////
  41. // //
  42. // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
  43. // // Digital Ltd. LLC
  44. // //
  45. // // All rights reserved.
  46. // //
  47. // // Redistribution and use in source and binary forms, with or without
  48. // // modification, are permitted provided that the following conditions are
  49. // // met:
  50. // // * Redistributions of source code must retain the above copyright
  51. // // notice, this list of conditions and the following disclaimer.
  52. // // * Redistributions in binary form must reproduce the above
  53. // // copyright notice, this list of conditions and the following disclaimer
  54. // // in the documentation and/or other materials provided with the
  55. // // distribution.
  56. // // * Neither the name of Industrial Light & Magic nor the names of
  57. // // its contributors may be used to endorse or promote products derived
  58. // // from this software without specific prior written permission.
  59. // //
  60. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  61. // // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  62. // // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  63. // // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  64. // // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  65. // // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  66. // // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  67. // // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  68. // // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  69. // // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  70. // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  71. // //
  72. // ///////////////////////////////////////////////////////////////////////////
  73. // // End of OpenEXR license -------------------------------------------------
  74. /**
  75. * A loader for the OpenEXR texture format.
  76. *
  77. * `EXRLoader` currently supports uncompressed, ZIP(S), RLE, PIZ and DWA/B compression.
  78. * Supports reading as UnsignedByte, HalfFloat and Float type data texture.
  79. *
  80. * ```js
  81. * const loader = new EXRLoader();
  82. * const texture = await loader.loadAsync( 'textures/memorial.exr' );
  83. * ```
  84. *
  85. * @augments DataTextureLoader
  86. * @three_import import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';
  87. */
  88. class EXRLoader extends DataTextureLoader {
  89. /**
  90. * Constructs a new EXR loader.
  91. *
  92. * @param {LoadingManager} [manager] - The loading manager.
  93. */
  94. constructor( manager ) {
  95. super( manager );
  96. /**
  97. * The texture type.
  98. *
  99. * @type {(HalfFloatType|FloatType)}
  100. * @default HalfFloatType
  101. */
  102. this.type = HalfFloatType;
  103. }
  104. /**
  105. * Parses the given EXR texture data.
  106. *
  107. * @param {ArrayBuffer} buffer - The raw texture data.
  108. * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
  109. */
  110. parse( buffer ) {
  111. const USHORT_RANGE = ( 1 << 16 );
  112. const BITMAP_SIZE = ( USHORT_RANGE >> 3 );
  113. const HUF_ENCBITS = 16; // literal (value) bit length
  114. const HUF_DECBITS = 14; // decoding bit size (>= 8)
  115. const HUF_ENCSIZE = ( 1 << HUF_ENCBITS ) + 1; // encoding table size
  116. const HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
  117. const HUF_DECMASK = HUF_DECSIZE - 1;
  118. const NBITS = 16;
  119. const A_OFFSET = 1 << ( NBITS - 1 );
  120. const MOD_MASK = ( 1 << NBITS ) - 1;
  121. const SHORT_ZEROCODE_RUN = 59;
  122. const LONG_ZEROCODE_RUN = 63;
  123. const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
  124. const ULONG_SIZE = 8;
  125. const FLOAT32_SIZE = 4;
  126. const INT32_SIZE = 4;
  127. const INT16_SIZE = 2;
  128. const INT8_SIZE = 1;
  129. const STATIC_HUFFMAN = 0;
  130. const DEFLATE = 1;
  131. const UNKNOWN = 0;
  132. const LOSSY_DCT = 1;
  133. const RLE = 2;
  134. const logBase = Math.pow( 2.7182818, 2.2 );
  135. function reverseLutFromBitmap( bitmap, lut ) {
  136. let k = 0;
  137. for ( let i = 0; i < USHORT_RANGE; ++ i ) {
  138. if ( ( i == 0 ) || ( bitmap[ i >> 3 ] & ( 1 << ( i & 7 ) ) ) ) {
  139. lut[ k ++ ] = i;
  140. }
  141. }
  142. const n = k - 1;
  143. while ( k < USHORT_RANGE ) lut[ k ++ ] = 0;
  144. return n;
  145. }
  146. function hufClearDecTable( hdec ) {
  147. for ( let i = 0; i < HUF_DECSIZE; i ++ ) {
  148. hdec[ i ] = {};
  149. hdec[ i ].len = 0;
  150. hdec[ i ].lit = 0;
  151. hdec[ i ].p = null;
  152. }
  153. }
  154. const getBitsReturn = { l: 0, c: 0, lc: 0 };
  155. function getBits( nBits, c, lc, uInt8Array, inOffset ) {
  156. while ( lc < nBits ) {
  157. c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
  158. lc += 8;
  159. }
  160. lc -= nBits;
  161. getBitsReturn.l = ( c >> lc ) & ( ( 1 << nBits ) - 1 );
  162. getBitsReturn.c = c;
  163. getBitsReturn.lc = lc;
  164. }
  165. const hufTableBuffer = new Array( 59 );
  166. function hufCanonicalCodeTable( hcode ) {
  167. for ( let i = 0; i <= 58; ++ i ) hufTableBuffer[ i ] = 0;
  168. for ( let i = 0; i < HUF_ENCSIZE; ++ i ) hufTableBuffer[ hcode[ i ] ] += 1;
  169. let c = 0;
  170. for ( let i = 58; i > 0; -- i ) {
  171. const nc = ( ( c + hufTableBuffer[ i ] ) >> 1 );
  172. hufTableBuffer[ i ] = c;
  173. c = nc;
  174. }
  175. for ( let i = 0; i < HUF_ENCSIZE; ++ i ) {
  176. const l = hcode[ i ];
  177. if ( l > 0 ) hcode[ i ] = l | ( hufTableBuffer[ l ] ++ << 6 );
  178. }
  179. }
  180. function hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, hcode ) {
  181. const p = inOffset;
  182. let c = 0;
  183. let lc = 0;
  184. for ( ; im <= iM; im ++ ) {
  185. if ( p.value - inOffset.value > ni ) return false;
  186. getBits( 6, c, lc, uInt8Array, p );
  187. const l = getBitsReturn.l;
  188. c = getBitsReturn.c;
  189. lc = getBitsReturn.lc;
  190. hcode[ im ] = l;
  191. if ( l == LONG_ZEROCODE_RUN ) {
  192. if ( p.value - inOffset.value > ni ) {
  193. throw new Error( 'Something wrong with hufUnpackEncTable' );
  194. }
  195. getBits( 8, c, lc, uInt8Array, p );
  196. let zerun = getBitsReturn.l + SHORTEST_LONG_RUN;
  197. c = getBitsReturn.c;
  198. lc = getBitsReturn.lc;
  199. if ( im + zerun > iM + 1 ) {
  200. throw new Error( 'Something wrong with hufUnpackEncTable' );
  201. }
  202. while ( zerun -- ) hcode[ im ++ ] = 0;
  203. im --;
  204. } else if ( l >= SHORT_ZEROCODE_RUN ) {
  205. let zerun = l - SHORT_ZEROCODE_RUN + 2;
  206. if ( im + zerun > iM + 1 ) {
  207. throw new Error( 'Something wrong with hufUnpackEncTable' );
  208. }
  209. while ( zerun -- ) hcode[ im ++ ] = 0;
  210. im --;
  211. }
  212. }
  213. hufCanonicalCodeTable( hcode );
  214. }
  215. function hufLength( code ) {
  216. return code & 63;
  217. }
  218. function hufCode( code ) {
  219. return code >> 6;
  220. }
  221. function hufBuildDecTable( hcode, im, iM, hdecod ) {
  222. for ( ; im <= iM; im ++ ) {
  223. const c = hufCode( hcode[ im ] );
  224. const l = hufLength( hcode[ im ] );
  225. if ( c >> l ) {
  226. throw new Error( 'Invalid table entry' );
  227. }
  228. if ( l > HUF_DECBITS ) {
  229. const pl = hdecod[ ( c >> ( l - HUF_DECBITS ) ) ];
  230. if ( pl.len ) {
  231. throw new Error( 'Invalid table entry' );
  232. }
  233. pl.lit ++;
  234. if ( pl.p ) {
  235. const p = pl.p;
  236. pl.p = new Array( pl.lit );
  237. for ( let i = 0; i < pl.lit - 1; ++ i ) {
  238. pl.p[ i ] = p[ i ];
  239. }
  240. } else {
  241. pl.p = new Array( 1 );
  242. }
  243. pl.p[ pl.lit - 1 ] = im;
  244. } else if ( l ) {
  245. let plOffset = 0;
  246. for ( let i = 1 << ( HUF_DECBITS - l ); i > 0; i -- ) {
  247. const pl = hdecod[ ( c << ( HUF_DECBITS - l ) ) + plOffset ];
  248. if ( pl.len || pl.p ) {
  249. throw new Error( 'Invalid table entry' );
  250. }
  251. pl.len = l;
  252. pl.lit = im;
  253. plOffset ++;
  254. }
  255. }
  256. }
  257. return true;
  258. }
  259. const getCharReturn = { c: 0, lc: 0 };
  260. function getChar( c, lc, uInt8Array, inOffset ) {
  261. c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
  262. lc += 8;
  263. getCharReturn.c = c;
  264. getCharReturn.lc = lc;
  265. }
  266. const getCodeReturn = { c: 0, lc: 0 };
  267. function getCode( po, rlc, c, lc, uInt8Array, inOffset, outBuffer, outBufferOffset, outBufferEndOffset ) {
  268. if ( po == rlc ) {
  269. if ( lc < 8 ) {
  270. getChar( c, lc, uInt8Array, inOffset );
  271. c = getCharReturn.c;
  272. lc = getCharReturn.lc;
  273. }
  274. lc -= 8;
  275. let cs = ( c >> lc );
  276. cs = new Uint8Array( [ cs ] )[ 0 ];
  277. if ( outBufferOffset.value + cs > outBufferEndOffset ) {
  278. return false;
  279. }
  280. const s = outBuffer[ outBufferOffset.value - 1 ];
  281. while ( cs -- > 0 ) {
  282. outBuffer[ outBufferOffset.value ++ ] = s;
  283. }
  284. } else if ( outBufferOffset.value < outBufferEndOffset ) {
  285. outBuffer[ outBufferOffset.value ++ ] = po;
  286. } else {
  287. return false;
  288. }
  289. getCodeReturn.c = c;
  290. getCodeReturn.lc = lc;
  291. }
  292. function UInt16( value ) {
  293. return ( value & 0xFFFF );
  294. }
  295. function Int16( value ) {
  296. const ref = UInt16( value );
  297. return ( ref > 0x7FFF ) ? ref - 0x10000 : ref;
  298. }
  299. const wdec14Return = { a: 0, b: 0 };
  300. function wdec14( l, h ) {
  301. const ls = Int16( l );
  302. const hs = Int16( h );
  303. const hi = hs;
  304. const ai = ls + ( hi & 1 ) + ( hi >> 1 );
  305. const as = ai;
  306. const bs = ai - hi;
  307. wdec14Return.a = as;
  308. wdec14Return.b = bs;
  309. }
  310. function wdec16( l, h ) {
  311. const m = UInt16( l );
  312. const d = UInt16( h );
  313. const bb = ( m - ( d >> 1 ) ) & MOD_MASK;
  314. const aa = ( d + bb - A_OFFSET ) & MOD_MASK;
  315. wdec14Return.a = aa;
  316. wdec14Return.b = bb;
  317. }
  318. function wav2Decode( buffer, j, nx, ox, ny, oy, mx ) {
  319. const w14 = mx < ( 1 << 14 );
  320. const n = ( nx > ny ) ? ny : nx;
  321. let p = 1;
  322. let p2;
  323. let py;
  324. while ( p <= n ) p <<= 1;
  325. p >>= 1;
  326. p2 = p;
  327. p >>= 1;
  328. while ( p >= 1 ) {
  329. py = 0;
  330. const ey = py + oy * ( ny - p2 );
  331. const oy1 = oy * p;
  332. const oy2 = oy * p2;
  333. const ox1 = ox * p;
  334. const ox2 = ox * p2;
  335. let i00, i01, i10, i11;
  336. for ( ; py <= ey; py += oy2 ) {
  337. let px = py;
  338. const ex = py + ox * ( nx - p2 );
  339. for ( ; px <= ex; px += ox2 ) {
  340. const p01 = px + ox1;
  341. const p10 = px + oy1;
  342. const p11 = p10 + ox1;
  343. if ( w14 ) {
  344. wdec14( buffer[ px + j ], buffer[ p10 + j ] );
  345. i00 = wdec14Return.a;
  346. i10 = wdec14Return.b;
  347. wdec14( buffer[ p01 + j ], buffer[ p11 + j ] );
  348. i01 = wdec14Return.a;
  349. i11 = wdec14Return.b;
  350. wdec14( i00, i01 );
  351. buffer[ px + j ] = wdec14Return.a;
  352. buffer[ p01 + j ] = wdec14Return.b;
  353. wdec14( i10, i11 );
  354. buffer[ p10 + j ] = wdec14Return.a;
  355. buffer[ p11 + j ] = wdec14Return.b;
  356. } else {
  357. wdec16( buffer[ px + j ], buffer[ p10 + j ] );
  358. i00 = wdec14Return.a;
  359. i10 = wdec14Return.b;
  360. wdec16( buffer[ p01 + j ], buffer[ p11 + j ] );
  361. i01 = wdec14Return.a;
  362. i11 = wdec14Return.b;
  363. wdec16( i00, i01 );
  364. buffer[ px + j ] = wdec14Return.a;
  365. buffer[ p01 + j ] = wdec14Return.b;
  366. wdec16( i10, i11 );
  367. buffer[ p10 + j ] = wdec14Return.a;
  368. buffer[ p11 + j ] = wdec14Return.b;
  369. }
  370. }
  371. if ( nx & p ) {
  372. const p10 = px + oy1;
  373. if ( w14 )
  374. wdec14( buffer[ px + j ], buffer[ p10 + j ] );
  375. else
  376. wdec16( buffer[ px + j ], buffer[ p10 + j ] );
  377. i00 = wdec14Return.a;
  378. buffer[ p10 + j ] = wdec14Return.b;
  379. buffer[ px + j ] = i00;
  380. }
  381. }
  382. if ( ny & p ) {
  383. let px = py;
  384. const ex = py + ox * ( nx - p2 );
  385. for ( ; px <= ex; px += ox2 ) {
  386. const p01 = px + ox1;
  387. if ( w14 )
  388. wdec14( buffer[ px + j ], buffer[ p01 + j ] );
  389. else
  390. wdec16( buffer[ px + j ], buffer[ p01 + j ] );
  391. i00 = wdec14Return.a;
  392. buffer[ p01 + j ] = wdec14Return.b;
  393. buffer[ px + j ] = i00;
  394. }
  395. }
  396. p2 = p;
  397. p >>= 1;
  398. }
  399. return py;
  400. }
  401. function hufDecode( encodingTable, decodingTable, uInt8Array, inOffset, ni, rlc, no, outBuffer, outOffset ) {
  402. let c = 0;
  403. let lc = 0;
  404. const outBufferEndOffset = no;
  405. const inOffsetEnd = Math.trunc( inOffset.value + ( ni + 7 ) / 8 );
  406. while ( inOffset.value < inOffsetEnd ) {
  407. getChar( c, lc, uInt8Array, inOffset );
  408. c = getCharReturn.c;
  409. lc = getCharReturn.lc;
  410. while ( lc >= HUF_DECBITS ) {
  411. const index = ( c >> ( lc - HUF_DECBITS ) ) & HUF_DECMASK;
  412. const pl = decodingTable[ index ];
  413. if ( pl.len ) {
  414. lc -= pl.len;
  415. getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
  416. c = getCodeReturn.c;
  417. lc = getCodeReturn.lc;
  418. } else {
  419. if ( ! pl.p ) {
  420. throw new Error( 'hufDecode issues' );
  421. }
  422. let j;
  423. for ( j = 0; j < pl.lit; j ++ ) {
  424. const l = hufLength( encodingTable[ pl.p[ j ] ] );
  425. while ( lc < l && inOffset.value < inOffsetEnd ) {
  426. getChar( c, lc, uInt8Array, inOffset );
  427. c = getCharReturn.c;
  428. lc = getCharReturn.lc;
  429. }
  430. if ( lc >= l ) {
  431. if ( hufCode( encodingTable[ pl.p[ j ] ] ) == ( ( c >> ( lc - l ) ) & ( ( 1 << l ) - 1 ) ) ) {
  432. lc -= l;
  433. getCode( pl.p[ j ], rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
  434. c = getCodeReturn.c;
  435. lc = getCodeReturn.lc;
  436. break;
  437. }
  438. }
  439. }
  440. if ( j == pl.lit ) {
  441. throw new Error( 'hufDecode issues' );
  442. }
  443. }
  444. }
  445. }
  446. const i = ( 8 - ni ) & 7;
  447. c >>= i;
  448. lc -= i;
  449. while ( lc > 0 ) {
  450. const pl = decodingTable[ ( c << ( HUF_DECBITS - lc ) ) & HUF_DECMASK ];
  451. if ( pl.len ) {
  452. lc -= pl.len;
  453. getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
  454. c = getCodeReturn.c;
  455. lc = getCodeReturn.lc;
  456. } else {
  457. throw new Error( 'hufDecode issues' );
  458. }
  459. }
  460. return true;
  461. }
  462. function hufUncompress( uInt8Array, inDataView, inOffset, nCompressed, outBuffer, nRaw ) {
  463. const outOffset = { value: 0 };
  464. const initialInOffset = inOffset.value;
  465. const im = parseUint32( inDataView, inOffset );
  466. const iM = parseUint32( inDataView, inOffset );
  467. inOffset.value += 4;
  468. const nBits = parseUint32( inDataView, inOffset );
  469. inOffset.value += 4;
  470. if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) {
  471. throw new Error( 'Something wrong with HUF_ENCSIZE' );
  472. }
  473. const freq = new Array( HUF_ENCSIZE );
  474. const hdec = new Array( HUF_DECSIZE );
  475. hufClearDecTable( hdec );
  476. const ni = nCompressed - ( inOffset.value - initialInOffset );
  477. hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, freq );
  478. if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) {
  479. throw new Error( 'Something wrong with hufUncompress' );
  480. }
  481. hufBuildDecTable( freq, im, iM, hdec );
  482. hufDecode( freq, hdec, uInt8Array, inOffset, nBits, iM, nRaw, outBuffer, outOffset );
  483. }
  484. function applyLut( lut, data, nData ) {
  485. for ( let i = 0; i < nData; ++ i ) {
  486. data[ i ] = lut[ data[ i ] ];
  487. }
  488. }
  489. function predictor( source ) {
  490. for ( let t = 1; t < source.length; t ++ ) {
  491. const d = source[ t - 1 ] + source[ t ] - 128;
  492. source[ t ] = d;
  493. }
  494. }
  495. function interleaveScalar( source, out ) {
  496. let t1 = 0;
  497. let t2 = Math.floor( ( source.length + 1 ) / 2 );
  498. let s = 0;
  499. const stop = source.length - 1;
  500. while ( true ) {
  501. if ( s > stop ) break;
  502. out[ s ++ ] = source[ t1 ++ ];
  503. if ( s > stop ) break;
  504. out[ s ++ ] = source[ t2 ++ ];
  505. }
  506. }
  507. function decodeRunLength( source ) {
  508. let size = source.byteLength;
  509. const out = new Array();
  510. let p = 0;
  511. const reader = new DataView( source );
  512. while ( size > 0 ) {
  513. const l = reader.getInt8( p ++ );
  514. if ( l < 0 ) {
  515. const count = - l;
  516. size -= count + 1;
  517. for ( let i = 0; i < count; i ++ ) {
  518. out.push( reader.getUint8( p ++ ) );
  519. }
  520. } else {
  521. const count = l;
  522. size -= 2;
  523. const value = reader.getUint8( p ++ );
  524. for ( let i = 0; i < count + 1; i ++ ) {
  525. out.push( value );
  526. }
  527. }
  528. }
  529. return out;
  530. }
  531. function lossyDctDecode( cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) {
  532. let dataView = new DataView( outBuffer.buffer );
  533. const width = channelData[ cscSet.idx[ 0 ] ].width;
  534. const height = channelData[ cscSet.idx[ 0 ] ].height;
  535. const numComp = 3;
  536. const numFullBlocksX = Math.floor( width / 8.0 );
  537. const numBlocksX = Math.ceil( width / 8.0 );
  538. const numBlocksY = Math.ceil( height / 8.0 );
  539. const leftoverX = width - ( numBlocksX - 1 ) * 8;
  540. const leftoverY = height - ( numBlocksY - 1 ) * 8;
  541. const currAcComp = { value: 0 };
  542. const currDcComp = new Array( numComp );
  543. const dctData = new Array( numComp );
  544. const halfZigBlock = new Array( numComp );
  545. const rowBlock = new Array( numComp );
  546. const rowOffsets = new Array( numComp );
  547. for ( let comp = 0; comp < numComp; ++ comp ) {
  548. rowOffsets[ comp ] = rowPtrs[ cscSet.idx[ comp ] ];
  549. currDcComp[ comp ] = ( comp < 1 ) ? 0 : currDcComp[ comp - 1 ] + numBlocksX * numBlocksY;
  550. dctData[ comp ] = new Float32Array( 64 );
  551. halfZigBlock[ comp ] = new Uint16Array( 64 );
  552. rowBlock[ comp ] = new Uint16Array( numBlocksX * 64 );
  553. }
  554. for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) {
  555. let maxY = 8;
  556. if ( blocky == numBlocksY - 1 )
  557. maxY = leftoverY;
  558. let maxX = 8;
  559. for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) {
  560. if ( blockx == numBlocksX - 1 )
  561. maxX = leftoverX;
  562. for ( let comp = 0; comp < numComp; ++ comp ) {
  563. halfZigBlock[ comp ].fill( 0 );
  564. // set block DC component
  565. halfZigBlock[ comp ][ 0 ] = dcBuffer[ currDcComp[ comp ] ++ ];
  566. // set block AC components
  567. unRleAC( currAcComp, acBuffer, halfZigBlock[ comp ] );
  568. // UnZigZag block to float
  569. unZigZag( halfZigBlock[ comp ], dctData[ comp ] );
  570. // decode float dct
  571. dctInverse( dctData[ comp ] );
  572. }
  573. if ( numComp == 3 ) {
  574. csc709Inverse( dctData );
  575. }
  576. for ( let comp = 0; comp < numComp; ++ comp ) {
  577. convertToHalf( dctData[ comp ], rowBlock[ comp ], blockx * 64 );
  578. }
  579. } // blockx
  580. let offset = 0;
  581. for ( let comp = 0; comp < numComp; ++ comp ) {
  582. const type = channelData[ cscSet.idx[ comp ] ].type;
  583. for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
  584. offset = rowOffsets[ comp ][ y ];
  585. for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) {
  586. const src = blockx * 64 + ( ( y & 0x7 ) * 8 );
  587. dataView.setUint16( offset + 0 * INT16_SIZE * type, rowBlock[ comp ][ src + 0 ], true );
  588. dataView.setUint16( offset + 1 * INT16_SIZE * type, rowBlock[ comp ][ src + 1 ], true );
  589. dataView.setUint16( offset + 2 * INT16_SIZE * type, rowBlock[ comp ][ src + 2 ], true );
  590. dataView.setUint16( offset + 3 * INT16_SIZE * type, rowBlock[ comp ][ src + 3 ], true );
  591. dataView.setUint16( offset + 4 * INT16_SIZE * type, rowBlock[ comp ][ src + 4 ], true );
  592. dataView.setUint16( offset + 5 * INT16_SIZE * type, rowBlock[ comp ][ src + 5 ], true );
  593. dataView.setUint16( offset + 6 * INT16_SIZE * type, rowBlock[ comp ][ src + 6 ], true );
  594. dataView.setUint16( offset + 7 * INT16_SIZE * type, rowBlock[ comp ][ src + 7 ], true );
  595. offset += 8 * INT16_SIZE * type;
  596. }
  597. }
  598. // handle partial X blocks
  599. if ( numFullBlocksX != numBlocksX ) {
  600. for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
  601. const offset = rowOffsets[ comp ][ y ] + 8 * numFullBlocksX * INT16_SIZE * type;
  602. const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 );
  603. for ( let x = 0; x < maxX; ++ x ) {
  604. dataView.setUint16( offset + x * INT16_SIZE * type, rowBlock[ comp ][ src + x ], true );
  605. }
  606. }
  607. }
  608. } // comp
  609. } // blocky
  610. const halfRow = new Uint16Array( width );
  611. dataView = new DataView( outBuffer.buffer );
  612. // convert channels back to float, if needed
  613. for ( let comp = 0; comp < numComp; ++ comp ) {
  614. channelData[ cscSet.idx[ comp ] ].decoded = true;
  615. const type = channelData[ cscSet.idx[ comp ] ].type;
  616. if ( channelData[ comp ].type != 2 ) continue;
  617. for ( let y = 0; y < height; ++ y ) {
  618. const offset = rowOffsets[ comp ][ y ];
  619. for ( let x = 0; x < width; ++ x ) {
  620. halfRow[ x ] = dataView.getUint16( offset + x * INT16_SIZE * type, true );
  621. }
  622. for ( let x = 0; x < width; ++ x ) {
  623. dataView.setFloat32( offset + x * INT16_SIZE * type, decodeFloat16( halfRow[ x ] ), true );
  624. }
  625. }
  626. }
  627. }
  628. function unRleAC( currAcComp, acBuffer, halfZigBlock ) {
  629. let acValue;
  630. let dctComp = 1;
  631. while ( dctComp < 64 ) {
  632. acValue = acBuffer[ currAcComp.value ];
  633. if ( acValue == 0xff00 ) {
  634. dctComp = 64;
  635. } else if ( acValue >> 8 == 0xff ) {
  636. dctComp += acValue & 0xff;
  637. } else {
  638. halfZigBlock[ dctComp ] = acValue;
  639. dctComp ++;
  640. }
  641. currAcComp.value ++;
  642. }
  643. }
  644. function unZigZag( src, dst ) {
  645. dst[ 0 ] = decodeFloat16( src[ 0 ] );
  646. dst[ 1 ] = decodeFloat16( src[ 1 ] );
  647. dst[ 2 ] = decodeFloat16( src[ 5 ] );
  648. dst[ 3 ] = decodeFloat16( src[ 6 ] );
  649. dst[ 4 ] = decodeFloat16( src[ 14 ] );
  650. dst[ 5 ] = decodeFloat16( src[ 15 ] );
  651. dst[ 6 ] = decodeFloat16( src[ 27 ] );
  652. dst[ 7 ] = decodeFloat16( src[ 28 ] );
  653. dst[ 8 ] = decodeFloat16( src[ 2 ] );
  654. dst[ 9 ] = decodeFloat16( src[ 4 ] );
  655. dst[ 10 ] = decodeFloat16( src[ 7 ] );
  656. dst[ 11 ] = decodeFloat16( src[ 13 ] );
  657. dst[ 12 ] = decodeFloat16( src[ 16 ] );
  658. dst[ 13 ] = decodeFloat16( src[ 26 ] );
  659. dst[ 14 ] = decodeFloat16( src[ 29 ] );
  660. dst[ 15 ] = decodeFloat16( src[ 42 ] );
  661. dst[ 16 ] = decodeFloat16( src[ 3 ] );
  662. dst[ 17 ] = decodeFloat16( src[ 8 ] );
  663. dst[ 18 ] = decodeFloat16( src[ 12 ] );
  664. dst[ 19 ] = decodeFloat16( src[ 17 ] );
  665. dst[ 20 ] = decodeFloat16( src[ 25 ] );
  666. dst[ 21 ] = decodeFloat16( src[ 30 ] );
  667. dst[ 22 ] = decodeFloat16( src[ 41 ] );
  668. dst[ 23 ] = decodeFloat16( src[ 43 ] );
  669. dst[ 24 ] = decodeFloat16( src[ 9 ] );
  670. dst[ 25 ] = decodeFloat16( src[ 11 ] );
  671. dst[ 26 ] = decodeFloat16( src[ 18 ] );
  672. dst[ 27 ] = decodeFloat16( src[ 24 ] );
  673. dst[ 28 ] = decodeFloat16( src[ 31 ] );
  674. dst[ 29 ] = decodeFloat16( src[ 40 ] );
  675. dst[ 30 ] = decodeFloat16( src[ 44 ] );
  676. dst[ 31 ] = decodeFloat16( src[ 53 ] );
  677. dst[ 32 ] = decodeFloat16( src[ 10 ] );
  678. dst[ 33 ] = decodeFloat16( src[ 19 ] );
  679. dst[ 34 ] = decodeFloat16( src[ 23 ] );
  680. dst[ 35 ] = decodeFloat16( src[ 32 ] );
  681. dst[ 36 ] = decodeFloat16( src[ 39 ] );
  682. dst[ 37 ] = decodeFloat16( src[ 45 ] );
  683. dst[ 38 ] = decodeFloat16( src[ 52 ] );
  684. dst[ 39 ] = decodeFloat16( src[ 54 ] );
  685. dst[ 40 ] = decodeFloat16( src[ 20 ] );
  686. dst[ 41 ] = decodeFloat16( src[ 22 ] );
  687. dst[ 42 ] = decodeFloat16( src[ 33 ] );
  688. dst[ 43 ] = decodeFloat16( src[ 38 ] );
  689. dst[ 44 ] = decodeFloat16( src[ 46 ] );
  690. dst[ 45 ] = decodeFloat16( src[ 51 ] );
  691. dst[ 46 ] = decodeFloat16( src[ 55 ] );
  692. dst[ 47 ] = decodeFloat16( src[ 60 ] );
  693. dst[ 48 ] = decodeFloat16( src[ 21 ] );
  694. dst[ 49 ] = decodeFloat16( src[ 34 ] );
  695. dst[ 50 ] = decodeFloat16( src[ 37 ] );
  696. dst[ 51 ] = decodeFloat16( src[ 47 ] );
  697. dst[ 52 ] = decodeFloat16( src[ 50 ] );
  698. dst[ 53 ] = decodeFloat16( src[ 56 ] );
  699. dst[ 54 ] = decodeFloat16( src[ 59 ] );
  700. dst[ 55 ] = decodeFloat16( src[ 61 ] );
  701. dst[ 56 ] = decodeFloat16( src[ 35 ] );
  702. dst[ 57 ] = decodeFloat16( src[ 36 ] );
  703. dst[ 58 ] = decodeFloat16( src[ 48 ] );
  704. dst[ 59 ] = decodeFloat16( src[ 49 ] );
  705. dst[ 60 ] = decodeFloat16( src[ 57 ] );
  706. dst[ 61 ] = decodeFloat16( src[ 58 ] );
  707. dst[ 62 ] = decodeFloat16( src[ 62 ] );
  708. dst[ 63 ] = decodeFloat16( src[ 63 ] );
  709. }
  710. function dctInverse( data ) {
  711. const a = 0.5 * Math.cos( 3.14159 / 4.0 );
  712. const b = 0.5 * Math.cos( 3.14159 / 16.0 );
  713. const c = 0.5 * Math.cos( 3.14159 / 8.0 );
  714. const d = 0.5 * Math.cos( 3.0 * 3.14159 / 16.0 );
  715. const e = 0.5 * Math.cos( 5.0 * 3.14159 / 16.0 );
  716. const f = 0.5 * Math.cos( 3.0 * 3.14159 / 8.0 );
  717. const g = 0.5 * Math.cos( 7.0 * 3.14159 / 16.0 );
  718. const alpha = new Array( 4 );
  719. const beta = new Array( 4 );
  720. const theta = new Array( 4 );
  721. const gamma = new Array( 4 );
  722. for ( let row = 0; row < 8; ++ row ) {
  723. const rowPtr = row * 8;
  724. alpha[ 0 ] = c * data[ rowPtr + 2 ];
  725. alpha[ 1 ] = f * data[ rowPtr + 2 ];
  726. alpha[ 2 ] = c * data[ rowPtr + 6 ];
  727. alpha[ 3 ] = f * data[ rowPtr + 6 ];
  728. beta[ 0 ] = b * data[ rowPtr + 1 ] + d * data[ rowPtr + 3 ] + e * data[ rowPtr + 5 ] + g * data[ rowPtr + 7 ];
  729. beta[ 1 ] = d * data[ rowPtr + 1 ] - g * data[ rowPtr + 3 ] - b * data[ rowPtr + 5 ] - e * data[ rowPtr + 7 ];
  730. beta[ 2 ] = e * data[ rowPtr + 1 ] - b * data[ rowPtr + 3 ] + g * data[ rowPtr + 5 ] + d * data[ rowPtr + 7 ];
  731. beta[ 3 ] = g * data[ rowPtr + 1 ] - e * data[ rowPtr + 3 ] + d * data[ rowPtr + 5 ] - b * data[ rowPtr + 7 ];
  732. theta[ 0 ] = a * ( data[ rowPtr + 0 ] + data[ rowPtr + 4 ] );
  733. theta[ 3 ] = a * ( data[ rowPtr + 0 ] - data[ rowPtr + 4 ] );
  734. theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
  735. theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
  736. gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
  737. gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
  738. gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
  739. gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
  740. data[ rowPtr + 0 ] = gamma[ 0 ] + beta[ 0 ];
  741. data[ rowPtr + 1 ] = gamma[ 1 ] + beta[ 1 ];
  742. data[ rowPtr + 2 ] = gamma[ 2 ] + beta[ 2 ];
  743. data[ rowPtr + 3 ] = gamma[ 3 ] + beta[ 3 ];
  744. data[ rowPtr + 4 ] = gamma[ 3 ] - beta[ 3 ];
  745. data[ rowPtr + 5 ] = gamma[ 2 ] - beta[ 2 ];
  746. data[ rowPtr + 6 ] = gamma[ 1 ] - beta[ 1 ];
  747. data[ rowPtr + 7 ] = gamma[ 0 ] - beta[ 0 ];
  748. }
  749. for ( let column = 0; column < 8; ++ column ) {
  750. alpha[ 0 ] = c * data[ 16 + column ];
  751. alpha[ 1 ] = f * data[ 16 + column ];
  752. alpha[ 2 ] = c * data[ 48 + column ];
  753. alpha[ 3 ] = f * data[ 48 + column ];
  754. beta[ 0 ] = b * data[ 8 + column ] + d * data[ 24 + column ] + e * data[ 40 + column ] + g * data[ 56 + column ];
  755. beta[ 1 ] = d * data[ 8 + column ] - g * data[ 24 + column ] - b * data[ 40 + column ] - e * data[ 56 + column ];
  756. beta[ 2 ] = e * data[ 8 + column ] - b * data[ 24 + column ] + g * data[ 40 + column ] + d * data[ 56 + column ];
  757. beta[ 3 ] = g * data[ 8 + column ] - e * data[ 24 + column ] + d * data[ 40 + column ] - b * data[ 56 + column ];
  758. theta[ 0 ] = a * ( data[ column ] + data[ 32 + column ] );
  759. theta[ 3 ] = a * ( data[ column ] - data[ 32 + column ] );
  760. theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
  761. theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
  762. gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
  763. gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
  764. gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
  765. gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
  766. data[ 0 + column ] = gamma[ 0 ] + beta[ 0 ];
  767. data[ 8 + column ] = gamma[ 1 ] + beta[ 1 ];
  768. data[ 16 + column ] = gamma[ 2 ] + beta[ 2 ];
  769. data[ 24 + column ] = gamma[ 3 ] + beta[ 3 ];
  770. data[ 32 + column ] = gamma[ 3 ] - beta[ 3 ];
  771. data[ 40 + column ] = gamma[ 2 ] - beta[ 2 ];
  772. data[ 48 + column ] = gamma[ 1 ] - beta[ 1 ];
  773. data[ 56 + column ] = gamma[ 0 ] - beta[ 0 ];
  774. }
  775. }
  776. function csc709Inverse( data ) {
  777. for ( let i = 0; i < 64; ++ i ) {
  778. const y = data[ 0 ][ i ];
  779. const cb = data[ 1 ][ i ];
  780. const cr = data[ 2 ][ i ];
  781. data[ 0 ][ i ] = y + 1.5747 * cr;
  782. data[ 1 ][ i ] = y - 0.1873 * cb - 0.4682 * cr;
  783. data[ 2 ][ i ] = y + 1.8556 * cb;
  784. }
  785. }
  786. function convertToHalf( src, dst, idx ) {
  787. for ( let i = 0; i < 64; ++ i ) {
  788. dst[ idx + i ] = DataUtils.toHalfFloat( toLinear( src[ i ] ) );
  789. }
  790. }
  791. function toLinear( float ) {
  792. if ( float <= 1 ) {
  793. return Math.sign( float ) * Math.pow( Math.abs( float ), 2.2 );
  794. } else {
  795. return Math.sign( float ) * Math.pow( logBase, Math.abs( float ) - 1.0 );
  796. }
  797. }
  798. function uncompressRAW( info ) {
  799. return new DataView( info.array.buffer, info.offset.value, info.size );
  800. }
  801. function uncompressRLE( info ) {
  802. const compressed = info.viewer.buffer.slice( info.offset.value, info.offset.value + info.size );
  803. const rawBuffer = new Uint8Array( decodeRunLength( compressed ) );
  804. const tmpBuffer = new Uint8Array( rawBuffer.length );
  805. predictor( rawBuffer ); // revert predictor
  806. interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
  807. return new DataView( tmpBuffer.buffer );
  808. }
  809. function uncompressZIP( info ) {
  810. const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
  811. const rawBuffer = fflate.unzlibSync( compressed );
  812. const tmpBuffer = new Uint8Array( rawBuffer.length );
  813. predictor( rawBuffer ); // revert predictor
  814. interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
  815. return new DataView( tmpBuffer.buffer );
  816. }
  817. function uncompressPIZ( info ) {
  818. const inDataView = info.viewer;
  819. const inOffset = { value: info.offset.value };
  820. const outBuffer = new Uint16Array( info.columns * info.lines * ( info.inputChannels.length * info.type ) );
  821. const bitmap = new Uint8Array( BITMAP_SIZE );
  822. // Setup channel info
  823. let outBufferEnd = 0;
  824. const pizChannelData = new Array( info.inputChannels.length );
  825. for ( let i = 0, il = info.inputChannels.length; i < il; i ++ ) {
  826. pizChannelData[ i ] = {};
  827. pizChannelData[ i ][ 'start' ] = outBufferEnd;
  828. pizChannelData[ i ][ 'end' ] = pizChannelData[ i ][ 'start' ];
  829. pizChannelData[ i ][ 'nx' ] = info.columns;
  830. pizChannelData[ i ][ 'ny' ] = info.lines;
  831. pizChannelData[ i ][ 'size' ] = info.type;
  832. outBufferEnd += pizChannelData[ i ].nx * pizChannelData[ i ].ny * pizChannelData[ i ].size;
  833. }
  834. // Read range compression data
  835. const minNonZero = parseUint16( inDataView, inOffset );
  836. const maxNonZero = parseUint16( inDataView, inOffset );
  837. if ( maxNonZero >= BITMAP_SIZE ) {
  838. throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' );
  839. }
  840. if ( minNonZero <= maxNonZero ) {
  841. for ( let i = 0; i < maxNonZero - minNonZero + 1; i ++ ) {
  842. bitmap[ i + minNonZero ] = parseUint8( inDataView, inOffset );
  843. }
  844. }
  845. // Reverse LUT
  846. const lut = new Uint16Array( USHORT_RANGE );
  847. const maxValue = reverseLutFromBitmap( bitmap, lut );
  848. const length = parseUint32( inDataView, inOffset );
  849. // Huffman decoding
  850. hufUncompress( info.array, inDataView, inOffset, length, outBuffer, outBufferEnd );
  851. // Wavelet decoding
  852. for ( let i = 0; i < info.inputChannels.length; ++ i ) {
  853. const cd = pizChannelData[ i ];
  854. for ( let j = 0; j < pizChannelData[ i ].size; ++ j ) {
  855. wav2Decode(
  856. outBuffer,
  857. cd.start + j,
  858. cd.nx,
  859. cd.size,
  860. cd.ny,
  861. cd.nx * cd.size,
  862. maxValue
  863. );
  864. }
  865. }
  866. // Expand the pixel data to their original range
  867. applyLut( lut, outBuffer, outBufferEnd );
  868. // Rearrange the pixel data into the format expected by the caller.
  869. let tmpOffset = 0;
  870. const tmpBuffer = new Uint8Array( outBuffer.buffer.byteLength );
  871. for ( let y = 0; y < info.lines; y ++ ) {
  872. for ( let c = 0; c < info.inputChannels.length; c ++ ) {
  873. const cd = pizChannelData[ c ];
  874. const n = cd.nx * cd.size;
  875. const cp = new Uint8Array( outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE );
  876. tmpBuffer.set( cp, tmpOffset );
  877. tmpOffset += n * INT16_SIZE;
  878. cd.end += n;
  879. }
  880. }
  881. return new DataView( tmpBuffer.buffer );
  882. }
  883. function uncompressPXR( info ) {
  884. const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
  885. const rawBuffer = fflate.unzlibSync( compressed );
  886. const byteSize = info.inputChannels.length * info.lines * info.columns * info.totalBytes;
  887. const tmpBuffer = new ArrayBuffer( byteSize );
  888. const viewer = new DataView( tmpBuffer );
  889. let tmpBufferEnd = 0;
  890. let writePtr = 0;
  891. const ptr = new Array( 4 );
  892. for ( let y = 0; y < info.lines; y ++ ) {
  893. for ( let c = 0; c < info.inputChannels.length; c ++ ) {
  894. let pixel = 0;
  895. const type = info.inputChannels[ c ].pixelType;
  896. switch ( type ) {
  897. case 1:
  898. ptr[ 0 ] = tmpBufferEnd;
  899. ptr[ 1 ] = ptr[ 0 ] + info.columns;
  900. tmpBufferEnd = ptr[ 1 ] + info.columns;
  901. for ( let j = 0; j < info.columns; ++ j ) {
  902. const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 8 ) | rawBuffer[ ptr[ 1 ] ++ ];
  903. pixel += diff;
  904. viewer.setUint16( writePtr, pixel, true );
  905. writePtr += 2;
  906. }
  907. break;
  908. case 2:
  909. ptr[ 0 ] = tmpBufferEnd;
  910. ptr[ 1 ] = ptr[ 0 ] + info.columns;
  911. ptr[ 2 ] = ptr[ 1 ] + info.columns;
  912. tmpBufferEnd = ptr[ 2 ] + info.columns;
  913. for ( let j = 0; j < info.columns; ++ j ) {
  914. const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 24 ) | ( rawBuffer[ ptr[ 1 ] ++ ] << 16 ) | ( rawBuffer[ ptr[ 2 ] ++ ] << 8 );
  915. pixel += diff;
  916. viewer.setUint32( writePtr, pixel, true );
  917. writePtr += 4;
  918. }
  919. break;
  920. }
  921. }
  922. }
  923. return viewer;
  924. }
  925. function uncompressDWA( info ) {
  926. const inDataView = info.viewer;
  927. const inOffset = { value: info.offset.value };
  928. const outBuffer = new Uint8Array( info.columns * info.lines * ( info.inputChannels.length * info.type * INT16_SIZE ) );
  929. // Read compression header information
  930. const dwaHeader = {
  931. version: parseInt64( inDataView, inOffset ),
  932. unknownUncompressedSize: parseInt64( inDataView, inOffset ),
  933. unknownCompressedSize: parseInt64( inDataView, inOffset ),
  934. acCompressedSize: parseInt64( inDataView, inOffset ),
  935. dcCompressedSize: parseInt64( inDataView, inOffset ),
  936. rleCompressedSize: parseInt64( inDataView, inOffset ),
  937. rleUncompressedSize: parseInt64( inDataView, inOffset ),
  938. rleRawSize: parseInt64( inDataView, inOffset ),
  939. totalAcUncompressedCount: parseInt64( inDataView, inOffset ),
  940. totalDcUncompressedCount: parseInt64( inDataView, inOffset ),
  941. acCompression: parseInt64( inDataView, inOffset )
  942. };
  943. if ( dwaHeader.version < 2 )
  944. throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' );
  945. // Read channel ruleset information
  946. const channelRules = new Array();
  947. let ruleSize = parseUint16( inDataView, inOffset ) - INT16_SIZE;
  948. while ( ruleSize > 0 ) {
  949. const name = parseNullTerminatedString( inDataView.buffer, inOffset );
  950. const value = parseUint8( inDataView, inOffset );
  951. const compression = ( value >> 2 ) & 3;
  952. const csc = ( value >> 4 ) - 1;
  953. const index = new Int8Array( [ csc ] )[ 0 ];
  954. const type = parseUint8( inDataView, inOffset );
  955. channelRules.push( {
  956. name: name,
  957. index: index,
  958. type: type,
  959. compression: compression,
  960. } );
  961. ruleSize -= name.length + 3;
  962. }
  963. // Classify channels
  964. const channels = EXRHeader.channels;
  965. const channelData = new Array( info.inputChannels.length );
  966. for ( let i = 0; i < info.inputChannels.length; ++ i ) {
  967. const cd = channelData[ i ] = {};
  968. const channel = channels[ i ];
  969. cd.name = channel.name;
  970. cd.compression = UNKNOWN;
  971. cd.decoded = false;
  972. cd.type = channel.pixelType;
  973. cd.pLinear = channel.pLinear;
  974. cd.width = info.columns;
  975. cd.height = info.lines;
  976. }
  977. const cscSet = {
  978. idx: new Array( 3 )
  979. };
  980. for ( let offset = 0; offset < info.inputChannels.length; ++ offset ) {
  981. const cd = channelData[ offset ];
  982. for ( let i = 0; i < channelRules.length; ++ i ) {
  983. const rule = channelRules[ i ];
  984. if ( cd.name == rule.name ) {
  985. cd.compression = rule.compression;
  986. if ( rule.index >= 0 ) {
  987. cscSet.idx[ rule.index ] = offset;
  988. }
  989. cd.offset = offset;
  990. }
  991. }
  992. }
  993. let acBuffer, dcBuffer, rleBuffer;
  994. // Read DCT - AC component data
  995. if ( dwaHeader.acCompressedSize > 0 ) {
  996. switch ( dwaHeader.acCompression ) {
  997. case STATIC_HUFFMAN:
  998. acBuffer = new Uint16Array( dwaHeader.totalAcUncompressedCount );
  999. hufUncompress( info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount );
  1000. break;
  1001. case DEFLATE:
  1002. const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount );
  1003. const data = fflate.unzlibSync( compressed );
  1004. acBuffer = new Uint16Array( data.buffer );
  1005. inOffset.value += dwaHeader.totalAcUncompressedCount;
  1006. break;
  1007. }
  1008. }
  1009. // Read DCT - DC component data
  1010. if ( dwaHeader.dcCompressedSize > 0 ) {
  1011. const zlibInfo = {
  1012. array: info.array,
  1013. offset: inOffset,
  1014. size: dwaHeader.dcCompressedSize
  1015. };
  1016. dcBuffer = new Uint16Array( uncompressZIP( zlibInfo ).buffer );
  1017. inOffset.value += dwaHeader.dcCompressedSize;
  1018. }
  1019. // Read RLE compressed data
  1020. if ( dwaHeader.rleRawSize > 0 ) {
  1021. const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.rleCompressedSize );
  1022. const data = fflate.unzlibSync( compressed );
  1023. rleBuffer = decodeRunLength( data.buffer );
  1024. inOffset.value += dwaHeader.rleCompressedSize;
  1025. }
  1026. // Prepare outbuffer data offset
  1027. let outBufferEnd = 0;
  1028. const rowOffsets = new Array( channelData.length );
  1029. for ( let i = 0; i < rowOffsets.length; ++ i ) {
  1030. rowOffsets[ i ] = new Array();
  1031. }
  1032. for ( let y = 0; y < info.lines; ++ y ) {
  1033. for ( let chan = 0; chan < channelData.length; ++ chan ) {
  1034. rowOffsets[ chan ].push( outBufferEnd );
  1035. outBufferEnd += channelData[ chan ].width * info.type * INT16_SIZE;
  1036. }
  1037. }
  1038. // Lossy DCT decode RGB channels
  1039. lossyDctDecode( cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer );
  1040. // Decode other channels
  1041. for ( let i = 0; i < channelData.length; ++ i ) {
  1042. const cd = channelData[ i ];
  1043. if ( cd.decoded ) continue;
  1044. switch ( cd.compression ) {
  1045. case RLE:
  1046. let row = 0;
  1047. let rleOffset = 0;
  1048. for ( let y = 0; y < info.lines; ++ y ) {
  1049. let rowOffsetBytes = rowOffsets[ i ][ row ];
  1050. for ( let x = 0; x < cd.width; ++ x ) {
  1051. for ( let byte = 0; byte < INT16_SIZE * cd.type; ++ byte ) {
  1052. outBuffer[ rowOffsetBytes ++ ] = rleBuffer[ rleOffset + byte * cd.width * cd.height ];
  1053. }
  1054. rleOffset ++;
  1055. }
  1056. row ++;
  1057. }
  1058. break;
  1059. case LOSSY_DCT: // skip
  1060. default:
  1061. throw new Error( 'EXRLoader.parse: unsupported channel compression' );
  1062. }
  1063. }
  1064. return new DataView( outBuffer.buffer );
  1065. }
  1066. function parseNullTerminatedString( buffer, offset ) {
  1067. const uintBuffer = new Uint8Array( buffer );
  1068. let endOffset = 0;
  1069. while ( uintBuffer[ offset.value + endOffset ] != 0 ) {
  1070. endOffset += 1;
  1071. }
  1072. const stringValue = new TextDecoder().decode(
  1073. uintBuffer.slice( offset.value, offset.value + endOffset )
  1074. );
  1075. offset.value = offset.value + endOffset + 1;
  1076. return stringValue;
  1077. }
  1078. function parseFixedLengthString( buffer, offset, size ) {
  1079. const stringValue = new TextDecoder().decode(
  1080. new Uint8Array( buffer ).slice( offset.value, offset.value + size )
  1081. );
  1082. offset.value = offset.value + size;
  1083. return stringValue;
  1084. }
  1085. function parseRational( dataView, offset ) {
  1086. const x = parseInt32( dataView, offset );
  1087. const y = parseUint32( dataView, offset );
  1088. return [ x, y ];
  1089. }
  1090. function parseTimecode( dataView, offset ) {
  1091. const x = parseUint32( dataView, offset );
  1092. const y = parseUint32( dataView, offset );
  1093. return [ x, y ];
  1094. }
  1095. function parseInt32( dataView, offset ) {
  1096. const Int32 = dataView.getInt32( offset.value, true );
  1097. offset.value = offset.value + INT32_SIZE;
  1098. return Int32;
  1099. }
  1100. function parseUint32( dataView, offset ) {
  1101. const Uint32 = dataView.getUint32( offset.value, true );
  1102. offset.value = offset.value + INT32_SIZE;
  1103. return Uint32;
  1104. }
  1105. function parseUint8Array( uInt8Array, offset ) {
  1106. const Uint8 = uInt8Array[ offset.value ];
  1107. offset.value = offset.value + INT8_SIZE;
  1108. return Uint8;
  1109. }
  1110. function parseUint8( dataView, offset ) {
  1111. const Uint8 = dataView.getUint8( offset.value );
  1112. offset.value = offset.value + INT8_SIZE;
  1113. return Uint8;
  1114. }
  1115. const parseInt64 = function ( dataView, offset ) {
  1116. let int;
  1117. if ( 'getBigInt64' in DataView.prototype ) {
  1118. int = Number( dataView.getBigInt64( offset.value, true ) );
  1119. } else {
  1120. int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 );
  1121. }
  1122. offset.value += ULONG_SIZE;
  1123. return int;
  1124. };
  1125. function parseFloat32( dataView, offset ) {
  1126. const float = dataView.getFloat32( offset.value, true );
  1127. offset.value += FLOAT32_SIZE;
  1128. return float;
  1129. }
  1130. function decodeFloat32( dataView, offset ) {
  1131. return DataUtils.toHalfFloat( parseFloat32( dataView, offset ) );
  1132. }
  1133. // https://stackoverflow.com/questions/5678432/decompressing-half-precision-floats-in-javascript
  1134. function decodeFloat16( binary ) {
  1135. const exponent = ( binary & 0x7C00 ) >> 10,
  1136. fraction = binary & 0x03FF;
  1137. return ( binary >> 15 ? - 1 : 1 ) * (
  1138. exponent ?
  1139. (
  1140. exponent === 0x1F ?
  1141. fraction ? NaN : Infinity :
  1142. Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 )
  1143. ) :
  1144. 6.103515625e-5 * ( fraction / 0x400 )
  1145. );
  1146. }
  1147. function parseUint16( dataView, offset ) {
  1148. const Uint16 = dataView.getUint16( offset.value, true );
  1149. offset.value += INT16_SIZE;
  1150. return Uint16;
  1151. }
  1152. function parseFloat16( buffer, offset ) {
  1153. return decodeFloat16( parseUint16( buffer, offset ) );
  1154. }
  1155. function parseChlist( dataView, buffer, offset, size ) {
  1156. const startOffset = offset.value;
  1157. const channels = [];
  1158. while ( offset.value < ( startOffset + size - 1 ) ) {
  1159. const name = parseNullTerminatedString( buffer, offset );
  1160. const pixelType = parseInt32( dataView, offset );
  1161. const pLinear = parseUint8( dataView, offset );
  1162. offset.value += 3; // reserved, three chars
  1163. const xSampling = parseInt32( dataView, offset );
  1164. const ySampling = parseInt32( dataView, offset );
  1165. channels.push( {
  1166. name: name,
  1167. pixelType: pixelType,
  1168. pLinear: pLinear,
  1169. xSampling: xSampling,
  1170. ySampling: ySampling
  1171. } );
  1172. }
  1173. offset.value += 1;
  1174. return channels;
  1175. }
  1176. function parseChromaticities( dataView, offset ) {
  1177. const redX = parseFloat32( dataView, offset );
  1178. const redY = parseFloat32( dataView, offset );
  1179. const greenX = parseFloat32( dataView, offset );
  1180. const greenY = parseFloat32( dataView, offset );
  1181. const blueX = parseFloat32( dataView, offset );
  1182. const blueY = parseFloat32( dataView, offset );
  1183. const whiteX = parseFloat32( dataView, offset );
  1184. const whiteY = parseFloat32( dataView, offset );
  1185. return { redX: redX, redY: redY, greenX: greenX, greenY: greenY, blueX: blueX, blueY: blueY, whiteX: whiteX, whiteY: whiteY };
  1186. }
  1187. function parseCompression( dataView, offset ) {
  1188. const compressionCodes = [
  1189. 'NO_COMPRESSION',
  1190. 'RLE_COMPRESSION',
  1191. 'ZIPS_COMPRESSION',
  1192. 'ZIP_COMPRESSION',
  1193. 'PIZ_COMPRESSION',
  1194. 'PXR24_COMPRESSION',
  1195. 'B44_COMPRESSION',
  1196. 'B44A_COMPRESSION',
  1197. 'DWAA_COMPRESSION',
  1198. 'DWAB_COMPRESSION'
  1199. ];
  1200. const compression = parseUint8( dataView, offset );
  1201. return compressionCodes[ compression ];
  1202. }
  1203. function parseBox2i( dataView, offset ) {
  1204. const xMin = parseInt32( dataView, offset );
  1205. const yMin = parseInt32( dataView, offset );
  1206. const xMax = parseInt32( dataView, offset );
  1207. const yMax = parseInt32( dataView, offset );
  1208. return { xMin: xMin, yMin: yMin, xMax: xMax, yMax: yMax };
  1209. }
  1210. function parseLineOrder( dataView, offset ) {
  1211. const lineOrders = [
  1212. 'INCREASING_Y',
  1213. 'DECREASING_Y',
  1214. 'RANDOM_Y',
  1215. ];
  1216. const lineOrder = parseUint8( dataView, offset );
  1217. return lineOrders[ lineOrder ];
  1218. }
  1219. function parseEnvmap( dataView, offset ) {
  1220. const envmaps = [
  1221. 'ENVMAP_LATLONG',
  1222. 'ENVMAP_CUBE'
  1223. ];
  1224. const envmap = parseUint8( dataView, offset );
  1225. return envmaps[ envmap ];
  1226. }
  1227. function parseTiledesc( dataView, offset ) {
  1228. const levelModes = [
  1229. 'ONE_LEVEL',
  1230. 'MIPMAP_LEVELS',
  1231. 'RIPMAP_LEVELS',
  1232. ];
  1233. const roundingModes = [
  1234. 'ROUND_DOWN',
  1235. 'ROUND_UP',
  1236. ];
  1237. const xSize = parseUint32( dataView, offset );
  1238. const ySize = parseUint32( dataView, offset );
  1239. const modes = parseUint8( dataView, offset );
  1240. return {
  1241. xSize: xSize,
  1242. ySize: ySize,
  1243. levelMode: levelModes[ modes & 0xf ],
  1244. roundingMode: roundingModes[ modes >> 4 ]
  1245. };
  1246. }
  1247. function parseV2f( dataView, offset ) {
  1248. const x = parseFloat32( dataView, offset );
  1249. const y = parseFloat32( dataView, offset );
  1250. return [ x, y ];
  1251. }
  1252. function parseV3f( dataView, offset ) {
  1253. const x = parseFloat32( dataView, offset );
  1254. const y = parseFloat32( dataView, offset );
  1255. const z = parseFloat32( dataView, offset );
  1256. return [ x, y, z ];
  1257. }
  1258. function parseValue( dataView, buffer, offset, type, size ) {
  1259. if ( type === 'string' || type === 'stringvector' || type === 'iccProfile' ) {
  1260. return parseFixedLengthString( buffer, offset, size );
  1261. } else if ( type === 'chlist' ) {
  1262. return parseChlist( dataView, buffer, offset, size );
  1263. } else if ( type === 'chromaticities' ) {
  1264. return parseChromaticities( dataView, offset );
  1265. } else if ( type === 'compression' ) {
  1266. return parseCompression( dataView, offset );
  1267. } else if ( type === 'box2i' ) {
  1268. return parseBox2i( dataView, offset );
  1269. } else if ( type === 'envmap' ) {
  1270. return parseEnvmap( dataView, offset );
  1271. } else if ( type === 'tiledesc' ) {
  1272. return parseTiledesc( dataView, offset );
  1273. } else if ( type === 'lineOrder' ) {
  1274. return parseLineOrder( dataView, offset );
  1275. } else if ( type === 'float' ) {
  1276. return parseFloat32( dataView, offset );
  1277. } else if ( type === 'v2f' ) {
  1278. return parseV2f( dataView, offset );
  1279. } else if ( type === 'v3f' ) {
  1280. return parseV3f( dataView, offset );
  1281. } else if ( type === 'int' ) {
  1282. return parseInt32( dataView, offset );
  1283. } else if ( type === 'rational' ) {
  1284. return parseRational( dataView, offset );
  1285. } else if ( type === 'timecode' ) {
  1286. return parseTimecode( dataView, offset );
  1287. } else if ( type === 'preview' ) {
  1288. offset.value += size;
  1289. return 'skipped';
  1290. } else {
  1291. offset.value += size;
  1292. return undefined;
  1293. }
  1294. }
  1295. function roundLog2( x, mode ) {
  1296. const log2 = Math.log2( x );
  1297. return mode == 'ROUND_DOWN' ? Math.floor( log2 ) : Math.ceil( log2 );
  1298. }
  1299. function calculateTileLevels( tiledesc, w, h ) {
  1300. let num = 0;
  1301. switch ( tiledesc.levelMode ) {
  1302. case 'ONE_LEVEL':
  1303. num = 1;
  1304. break;
  1305. case 'MIPMAP_LEVELS':
  1306. num = roundLog2( Math.max( w, h ), tiledesc.roundingMode ) + 1;
  1307. break;
  1308. case 'RIPMAP_LEVELS':
  1309. throw new Error( 'THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.' );
  1310. }
  1311. return num;
  1312. }
  1313. function calculateTiles( count, dataSize, size, roundingMode ) {
  1314. const tiles = new Array( count );
  1315. for ( let i = 0; i < count; i ++ ) {
  1316. const b = ( 1 << i );
  1317. let s = ( dataSize / b ) | 0;
  1318. if ( roundingMode == 'ROUND_UP' && s * b < dataSize ) s += 1;
  1319. const l = Math.max( s, 1 );
  1320. tiles[ i ] = ( ( l + size - 1 ) / size ) | 0;
  1321. }
  1322. return tiles;
  1323. }
  1324. function parseTiles() {
  1325. const EXRDecoder = this;
  1326. const offset = EXRDecoder.offset;
  1327. const tmpOffset = { value: 0 };
  1328. for ( let tile = 0; tile < EXRDecoder.tileCount; tile ++ ) {
  1329. const tileX = parseInt32( EXRDecoder.viewer, offset );
  1330. const tileY = parseInt32( EXRDecoder.viewer, offset );
  1331. offset.value += 8; // skip levels - only parsing top-level
  1332. EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset );
  1333. const startX = tileX * EXRDecoder.blockWidth;
  1334. const startY = tileY * EXRDecoder.blockHeight;
  1335. EXRDecoder.columns = ( startX + EXRDecoder.blockWidth > EXRDecoder.width ) ? EXRDecoder.width - startX : EXRDecoder.blockWidth;
  1336. EXRDecoder.lines = ( startY + EXRDecoder.blockHeight > EXRDecoder.height ) ? EXRDecoder.height - startY : EXRDecoder.blockHeight;
  1337. const bytesBlockLine = EXRDecoder.columns * EXRDecoder.totalBytes;
  1338. const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesBlockLine;
  1339. const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
  1340. offset.value += EXRDecoder.size;
  1341. for ( let line = 0; line < EXRDecoder.lines; line ++ ) {
  1342. const lineOffset = line * EXRDecoder.columns * EXRDecoder.totalBytes;
  1343. for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
  1344. const name = EXRHeader.channels[ channelID ].name;
  1345. const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
  1346. const cOff = EXRDecoder.decodeChannels[ name ];
  1347. if ( cOff === undefined ) continue;
  1348. tmpOffset.value = lineOffset + lOff;
  1349. const outLineOffset = ( EXRDecoder.height - ( 1 + startY + line ) ) * EXRDecoder.outLineWidth;
  1350. for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
  1351. const outIndex = outLineOffset + ( x + startX ) * EXRDecoder.outputChannels + cOff;
  1352. EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
  1353. }
  1354. }
  1355. }
  1356. }
  1357. }
  1358. function parseScanline() {
  1359. const EXRDecoder = this;
  1360. const offset = EXRDecoder.offset;
  1361. const tmpOffset = { value: 0 };
  1362. for ( let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.blockHeight; scanlineBlockIdx ++ ) {
  1363. const line = parseInt32( EXRDecoder.viewer, offset ) - EXRHeader.dataWindow.yMin; // line_no
  1364. EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset ); // data_len
  1365. EXRDecoder.lines = ( ( line + EXRDecoder.blockHeight > EXRDecoder.height ) ? ( EXRDecoder.height - line ) : EXRDecoder.blockHeight );
  1366. const bytesPerLine = EXRDecoder.columns * EXRDecoder.totalBytes;
  1367. const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesPerLine;
  1368. const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
  1369. offset.value += EXRDecoder.size;
  1370. for ( let line_y = 0; line_y < EXRDecoder.blockHeight; line_y ++ ) {
  1371. const scan_y = scanlineBlockIdx * EXRDecoder.blockHeight;
  1372. const true_y = line_y + EXRDecoder.scanOrder( scan_y );
  1373. if ( true_y >= EXRDecoder.height ) continue;
  1374. const lineOffset = line_y * bytesPerLine;
  1375. const outLineOffset = ( EXRDecoder.height - 1 - true_y ) * EXRDecoder.outLineWidth;
  1376. for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
  1377. const name = EXRHeader.channels[ channelID ].name;
  1378. const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
  1379. const cOff = EXRDecoder.decodeChannels[ name ];
  1380. if ( cOff === undefined ) continue;
  1381. tmpOffset.value = lineOffset + lOff;
  1382. for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
  1383. const outIndex = outLineOffset + x * EXRDecoder.outputChannels + cOff;
  1384. EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. function parseHeader( dataView, buffer, offset ) {
  1391. const EXRHeader = {};
  1392. if ( dataView.getUint32( 0, true ) != 20000630 ) { // magic
  1393. throw new Error( 'THREE.EXRLoader: Provided file doesn\'t appear to be in OpenEXR format.' );
  1394. }
  1395. EXRHeader.version = dataView.getUint8( 4 );
  1396. const spec = dataView.getUint8( 5 ); // fullMask
  1397. EXRHeader.spec = {
  1398. singleTile: !! ( spec & 2 ),
  1399. longName: !! ( spec & 4 ),
  1400. deepFormat: !! ( spec & 8 ),
  1401. multiPart: !! ( spec & 16 ),
  1402. };
  1403. // start of header
  1404. offset.value = 8; // start at 8 - after pre-amble
  1405. let keepReading = true;
  1406. while ( keepReading ) {
  1407. const attributeName = parseNullTerminatedString( buffer, offset );
  1408. if ( attributeName === '' ) {
  1409. keepReading = false;
  1410. } else {
  1411. const attributeType = parseNullTerminatedString( buffer, offset );
  1412. const attributeSize = parseUint32( dataView, offset );
  1413. const attributeValue = parseValue( dataView, buffer, offset, attributeType, attributeSize );
  1414. if ( attributeValue === undefined ) {
  1415. console.warn( `THREE.EXRLoader: Skipped unknown header attribute type \'${attributeType}\'.` );
  1416. } else {
  1417. EXRHeader[ attributeName ] = attributeValue;
  1418. }
  1419. }
  1420. }
  1421. if ( ( spec & ~ 0x06 ) != 0 ) { // unsupported deep-image, multi-part
  1422. console.error( 'THREE.EXRHeader:', EXRHeader );
  1423. throw new Error( 'THREE.EXRLoader: Provided file is currently unsupported.' );
  1424. }
  1425. return EXRHeader;
  1426. }
  1427. function setupDecoder( EXRHeader, dataView, uInt8Array, offset, outputType ) {
  1428. const EXRDecoder = {
  1429. size: 0,
  1430. viewer: dataView,
  1431. array: uInt8Array,
  1432. offset: offset,
  1433. width: EXRHeader.dataWindow.xMax - EXRHeader.dataWindow.xMin + 1,
  1434. height: EXRHeader.dataWindow.yMax - EXRHeader.dataWindow.yMin + 1,
  1435. inputChannels: EXRHeader.channels,
  1436. channelByteOffsets: {},
  1437. scanOrder: null,
  1438. totalBytes: null,
  1439. columns: null,
  1440. lines: null,
  1441. type: null,
  1442. uncompress: null,
  1443. getter: null,
  1444. format: null,
  1445. colorSpace: LinearSRGBColorSpace,
  1446. };
  1447. switch ( EXRHeader.compression ) {
  1448. case 'NO_COMPRESSION':
  1449. EXRDecoder.blockHeight = 1;
  1450. EXRDecoder.uncompress = uncompressRAW;
  1451. break;
  1452. case 'RLE_COMPRESSION':
  1453. EXRDecoder.blockHeight = 1;
  1454. EXRDecoder.uncompress = uncompressRLE;
  1455. break;
  1456. case 'ZIPS_COMPRESSION':
  1457. EXRDecoder.blockHeight = 1;
  1458. EXRDecoder.uncompress = uncompressZIP;
  1459. break;
  1460. case 'ZIP_COMPRESSION':
  1461. EXRDecoder.blockHeight = 16;
  1462. EXRDecoder.uncompress = uncompressZIP;
  1463. break;
  1464. case 'PIZ_COMPRESSION':
  1465. EXRDecoder.blockHeight = 32;
  1466. EXRDecoder.uncompress = uncompressPIZ;
  1467. break;
  1468. case 'PXR24_COMPRESSION':
  1469. EXRDecoder.blockHeight = 16;
  1470. EXRDecoder.uncompress = uncompressPXR;
  1471. break;
  1472. case 'DWAA_COMPRESSION':
  1473. EXRDecoder.blockHeight = 32;
  1474. EXRDecoder.uncompress = uncompressDWA;
  1475. break;
  1476. case 'DWAB_COMPRESSION':
  1477. EXRDecoder.blockHeight = 256;
  1478. EXRDecoder.uncompress = uncompressDWA;
  1479. break;
  1480. default:
  1481. throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' );
  1482. }
  1483. const channels = {};
  1484. for ( const channel of EXRHeader.channels ) {
  1485. switch ( channel.name ) {
  1486. case 'Y':
  1487. case 'R':
  1488. case 'G':
  1489. case 'B':
  1490. case 'A':
  1491. channels[ channel.name ] = true;
  1492. EXRDecoder.type = channel.pixelType;
  1493. }
  1494. }
  1495. // RGB images will be converted to RGBA format, preventing software emulation in select devices.
  1496. let fillAlpha = false;
  1497. if ( channels.R && channels.G && channels.B ) {
  1498. fillAlpha = ! channels.A;
  1499. EXRDecoder.outputChannels = 4;
  1500. EXRDecoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
  1501. } else if ( channels.Y ) {
  1502. EXRDecoder.outputChannels = 1;
  1503. EXRDecoder.decodeChannels = { Y: 0 };
  1504. } else {
  1505. throw new Error( 'EXRLoader.parse: file contains unsupported data channels.' );
  1506. }
  1507. if ( EXRDecoder.type == 1 ) {
  1508. // half
  1509. switch ( outputType ) {
  1510. case FloatType:
  1511. EXRDecoder.getter = parseFloat16;
  1512. break;
  1513. case HalfFloatType:
  1514. EXRDecoder.getter = parseUint16;
  1515. break;
  1516. }
  1517. } else if ( EXRDecoder.type == 2 ) {
  1518. // float
  1519. switch ( outputType ) {
  1520. case FloatType:
  1521. EXRDecoder.getter = parseFloat32;
  1522. break;
  1523. case HalfFloatType:
  1524. EXRDecoder.getter = decodeFloat32;
  1525. }
  1526. } else {
  1527. throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' );
  1528. }
  1529. EXRDecoder.columns = EXRDecoder.width;
  1530. const size = EXRDecoder.width * EXRDecoder.height * EXRDecoder.outputChannels;
  1531. switch ( outputType ) {
  1532. case FloatType:
  1533. EXRDecoder.byteArray = new Float32Array( size );
  1534. // Fill initially with 1s for the alpha value if the texture is not RGBA, RGB values will be overwritten
  1535. if ( fillAlpha )
  1536. EXRDecoder.byteArray.fill( 1, 0, size );
  1537. break;
  1538. case HalfFloatType:
  1539. EXRDecoder.byteArray = new Uint16Array( size );
  1540. if ( fillAlpha )
  1541. EXRDecoder.byteArray.fill( 0x3C00, 0, size ); // Uint16Array holds half float data, 0x3C00 is 1
  1542. break;
  1543. default:
  1544. console.error( 'THREE.EXRLoader: unsupported type: ', outputType );
  1545. break;
  1546. }
  1547. let byteOffset = 0;
  1548. for ( const channel of EXRHeader.channels ) {
  1549. if ( EXRDecoder.decodeChannels[ channel.name ] !== undefined ) {
  1550. EXRDecoder.channelByteOffsets[ channel.name ] = byteOffset;
  1551. }
  1552. byteOffset += channel.pixelType * 2;
  1553. }
  1554. EXRDecoder.totalBytes = byteOffset;
  1555. EXRDecoder.outLineWidth = EXRDecoder.width * EXRDecoder.outputChannels;
  1556. if ( EXRHeader.lineOrder === 'INCREASING_Y' ) {
  1557. EXRDecoder.scanOrder = ( y ) => y;
  1558. } else {
  1559. EXRDecoder.scanOrder = ( y ) => EXRDecoder.height - 1 - y;
  1560. }
  1561. if ( EXRDecoder.outputChannels == 4 ) {
  1562. EXRDecoder.format = RGBAFormat;
  1563. EXRDecoder.colorSpace = LinearSRGBColorSpace;
  1564. } else {
  1565. EXRDecoder.format = RedFormat;
  1566. EXRDecoder.colorSpace = NoColorSpace;
  1567. }
  1568. if ( EXRHeader.spec.singleTile ) {
  1569. EXRDecoder.blockHeight = EXRHeader.tiles.ySize;
  1570. EXRDecoder.blockWidth = EXRHeader.tiles.xSize;
  1571. const numXLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
  1572. // const numYLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
  1573. const numXTiles = calculateTiles( numXLevels, EXRDecoder.width, EXRHeader.tiles.xSize, EXRHeader.tiles.roundingMode );
  1574. const numYTiles = calculateTiles( numXLevels, EXRDecoder.height, EXRHeader.tiles.ySize, EXRHeader.tiles.roundingMode );
  1575. EXRDecoder.tileCount = numXTiles[ 0 ] * numYTiles[ 0 ];
  1576. for ( let l = 0; l < numXLevels; l ++ )
  1577. for ( let y = 0; y < numYTiles[ l ]; y ++ )
  1578. for ( let x = 0; x < numXTiles[ l ]; x ++ )
  1579. parseInt64( dataView, offset ); // tileOffset
  1580. EXRDecoder.decode = parseTiles.bind( EXRDecoder );
  1581. } else {
  1582. EXRDecoder.blockWidth = EXRDecoder.width;
  1583. const blockCount = Math.ceil( EXRDecoder.height / EXRDecoder.blockHeight );
  1584. for ( let i = 0; i < blockCount; i ++ )
  1585. parseInt64( dataView, offset ); // scanlineOffset
  1586. EXRDecoder.decode = parseScanline.bind( EXRDecoder );
  1587. }
  1588. return EXRDecoder;
  1589. }
  1590. // start parsing file [START]
  1591. const offset = { value: 0 };
  1592. const bufferDataView = new DataView( buffer );
  1593. const uInt8Array = new Uint8Array( buffer );
  1594. // get header information and validate format.
  1595. const EXRHeader = parseHeader( bufferDataView, buffer, offset );
  1596. // get input compression information and prepare decoding.
  1597. const EXRDecoder = setupDecoder( EXRHeader, bufferDataView, uInt8Array, offset, this.type );
  1598. // parse input data
  1599. EXRDecoder.decode();
  1600. return {
  1601. header: EXRHeader,
  1602. width: EXRDecoder.width,
  1603. height: EXRDecoder.height,
  1604. data: EXRDecoder.byteArray,
  1605. format: EXRDecoder.format,
  1606. colorSpace: EXRDecoder.colorSpace,
  1607. type: this.type,
  1608. };
  1609. }
  1610. /**
  1611. * Sets the texture type.
  1612. *
  1613. * @param {(HalfFloatType|FloatType)} value - The texture type to set.
  1614. * @return {RGBMLoader} A reference to this loader.
  1615. */
  1616. setDataType( value ) {
  1617. this.type = value;
  1618. return this;
  1619. }
  1620. load( url, onLoad, onProgress, onError ) {
  1621. function onLoadCallback( texture, texData ) {
  1622. texture.colorSpace = texData.colorSpace;
  1623. texture.minFilter = LinearFilter;
  1624. texture.magFilter = LinearFilter;
  1625. texture.generateMipmaps = false;
  1626. texture.flipY = false;
  1627. if ( onLoad ) onLoad( texture, texData );
  1628. }
  1629. return super.load( url, onLoadCallback, onProgress, onError );
  1630. }
  1631. }
  1632. export { EXRLoader };