EXRLoader.js 61 KB

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