RGBELoader.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /**
  2. * @author Nikos M. / https://github.com/foo123/
  3. */
  4. import {
  5. DataTextureLoader,
  6. FloatType,
  7. HalfFloatType,
  8. LinearEncoding,
  9. LinearFilter,
  10. NearestFilter,
  11. RGBEEncoding,
  12. RGBEFormat,
  13. RGBFormat,
  14. UnsignedByteType
  15. } from "../../../build/three.module.js";
  16. // https://github.com/mrdoob/three.js/issues/5552
  17. // http://en.wikipedia.org/wiki/RGBE_image_format
  18. var RGBELoader = function ( manager ) {
  19. DataTextureLoader.call( this, manager );
  20. this.type = UnsignedByteType;
  21. };
  22. RGBELoader.prototype = Object.assign( Object.create( DataTextureLoader.prototype ), {
  23. constructor: RGBELoader,
  24. // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html
  25. parse: function ( buffer ) {
  26. var
  27. /* return codes for rgbe routines */
  28. //RGBE_RETURN_SUCCESS = 0,
  29. RGBE_RETURN_FAILURE = - 1,
  30. /* default error routine. change this to change error handling */
  31. rgbe_read_error = 1,
  32. rgbe_write_error = 2,
  33. rgbe_format_error = 3,
  34. rgbe_memory_error = 4,
  35. rgbe_error = function ( rgbe_error_code, msg ) {
  36. switch ( rgbe_error_code ) {
  37. case rgbe_read_error: console.error( "RGBELoader Read Error: " + ( msg || '' ) );
  38. break;
  39. case rgbe_write_error: console.error( "RGBELoader Write Error: " + ( msg || '' ) );
  40. break;
  41. case rgbe_format_error: console.error( "RGBELoader Bad File Format: " + ( msg || '' ) );
  42. break;
  43. default:
  44. case rgbe_memory_error: console.error( "RGBELoader: Error: " + ( msg || '' ) );
  45. }
  46. return RGBE_RETURN_FAILURE;
  47. },
  48. /* offsets to red, green, and blue components in a data (float) pixel */
  49. //RGBE_DATA_RED = 0,
  50. //RGBE_DATA_GREEN = 1,
  51. //RGBE_DATA_BLUE = 2,
  52. /* number of floats per pixel, use 4 since stored in rgba image format */
  53. //RGBE_DATA_SIZE = 4,
  54. /* flags indicating which fields in an rgbe_header_info are valid */
  55. RGBE_VALID_PROGRAMTYPE = 1,
  56. RGBE_VALID_FORMAT = 2,
  57. RGBE_VALID_DIMENSIONS = 4,
  58. NEWLINE = "\n",
  59. fgets = function ( buffer, lineLimit, consume ) {
  60. lineLimit = ! lineLimit ? 1024 : lineLimit;
  61. var p = buffer.pos,
  62. i = - 1, len = 0, s = '', chunkSize = 128,
  63. chunk = String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) )
  64. ;
  65. while ( ( 0 > ( i = chunk.indexOf( NEWLINE ) ) ) && ( len < lineLimit ) && ( p < buffer.byteLength ) ) {
  66. s += chunk; len += chunk.length;
  67. p += chunkSize;
  68. chunk += String.fromCharCode.apply( null, new Uint16Array( buffer.subarray( p, p + chunkSize ) ) );
  69. }
  70. if ( - 1 < i ) {
  71. /*for (i=l-1; i>=0; i--) {
  72. byteCode = m.charCodeAt(i);
  73. if (byteCode > 0x7f && byteCode <= 0x7ff) byteLen++;
  74. else if (byteCode > 0x7ff && byteCode <= 0xffff) byteLen += 2;
  75. if (byteCode >= 0xDC00 && byteCode <= 0xDFFF) i--; //trail surrogate
  76. }*/
  77. if ( false !== consume ) buffer.pos += len + i + 1;
  78. return s + chunk.slice( 0, i );
  79. }
  80. return false;
  81. },
  82. /* minimal header reading. modify if you want to parse more information */
  83. RGBE_ReadHeader = function ( buffer ) {
  84. var line, match,
  85. // regexes to parse header info fields
  86. magic_token_re = /^#\?(\S+)$/,
  87. gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/,
  88. exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/,
  89. format_re = /^\s*FORMAT=(\S+)\s*$/,
  90. dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/,
  91. // RGBE format header struct
  92. header = {
  93. valid: 0, /* indicate which fields are valid */
  94. string: '', /* the actual header string */
  95. comments: '', /* comments found in header */
  96. programtype: 'RGBE', /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */
  97. format: '', /* RGBE format, default 32-bit_rle_rgbe */
  98. gamma: 1.0, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */
  99. exposure: 1.0, /* a value of 1.0 in an image corresponds to <exposure> watts/steradian/m^2. defaults to 1.0 */
  100. width: 0, height: 0 /* image dimensions, width/height */
  101. };
  102. if ( buffer.pos >= buffer.byteLength || ! ( line = fgets( buffer ) ) ) {
  103. return rgbe_error( rgbe_read_error, "no header found" );
  104. }
  105. /* if you want to require the magic token then uncomment the next line */
  106. if ( ! ( match = line.match( magic_token_re ) ) ) {
  107. return rgbe_error( rgbe_format_error, "bad initial token" );
  108. }
  109. header.valid |= RGBE_VALID_PROGRAMTYPE;
  110. header.programtype = match[ 1 ];
  111. header.string += line + "\n";
  112. while ( true ) {
  113. line = fgets( buffer );
  114. if ( false === line ) break;
  115. header.string += line + "\n";
  116. if ( '#' === line.charAt( 0 ) ) {
  117. header.comments += line + "\n";
  118. continue; // comment line
  119. }
  120. if ( match = line.match( gamma_re ) ) {
  121. header.gamma = parseFloat( match[ 1 ], 10 );
  122. }
  123. if ( match = line.match( exposure_re ) ) {
  124. header.exposure = parseFloat( match[ 1 ], 10 );
  125. }
  126. if ( match = line.match( format_re ) ) {
  127. header.valid |= RGBE_VALID_FORMAT;
  128. header.format = match[ 1 ];//'32-bit_rle_rgbe';
  129. }
  130. if ( match = line.match( dimensions_re ) ) {
  131. header.valid |= RGBE_VALID_DIMENSIONS;
  132. header.height = parseInt( match[ 1 ], 10 );
  133. header.width = parseInt( match[ 2 ], 10 );
  134. }
  135. if ( ( header.valid & RGBE_VALID_FORMAT ) && ( header.valid & RGBE_VALID_DIMENSIONS ) ) break;
  136. }
  137. if ( ! ( header.valid & RGBE_VALID_FORMAT ) ) {
  138. return rgbe_error( rgbe_format_error, "missing format specifier" );
  139. }
  140. if ( ! ( header.valid & RGBE_VALID_DIMENSIONS ) ) {
  141. return rgbe_error( rgbe_format_error, "missing image size specifier" );
  142. }
  143. return header;
  144. },
  145. RGBE_ReadPixels_RLE = function ( buffer, w, h ) {
  146. var data_rgba, offset, pos, count, byteValue,
  147. scanline_buffer, ptr, ptr_end, i, l, off, isEncodedRun,
  148. scanline_width = w, num_scanlines = h, rgbeStart
  149. ;
  150. if (
  151. // run length encoding is not allowed so read flat
  152. ( ( scanline_width < 8 ) || ( scanline_width > 0x7fff ) ) ||
  153. // this file is not run length encoded
  154. ( ( 2 !== buffer[ 0 ] ) || ( 2 !== buffer[ 1 ] ) || ( buffer[ 2 ] & 0x80 ) )
  155. ) {
  156. // return the flat buffer
  157. return new Uint8Array( buffer );
  158. }
  159. if ( scanline_width !== ( ( buffer[ 2 ] << 8 ) | buffer[ 3 ] ) ) {
  160. return rgbe_error( rgbe_format_error, "wrong scanline width" );
  161. }
  162. data_rgba = new Uint8Array( 4 * w * h );
  163. if ( ! data_rgba.length ) {
  164. return rgbe_error( rgbe_memory_error, "unable to allocate buffer space" );
  165. }
  166. offset = 0; pos = 0; ptr_end = 4 * scanline_width;
  167. rgbeStart = new Uint8Array( 4 );
  168. scanline_buffer = new Uint8Array( ptr_end );
  169. // read in each successive scanline
  170. while ( ( num_scanlines > 0 ) && ( pos < buffer.byteLength ) ) {
  171. if ( pos + 4 > buffer.byteLength ) {
  172. return rgbe_error( rgbe_read_error );
  173. }
  174. rgbeStart[ 0 ] = buffer[ pos ++ ];
  175. rgbeStart[ 1 ] = buffer[ pos ++ ];
  176. rgbeStart[ 2 ] = buffer[ pos ++ ];
  177. rgbeStart[ 3 ] = buffer[ pos ++ ];
  178. if ( ( 2 != rgbeStart[ 0 ] ) || ( 2 != rgbeStart[ 1 ] ) || ( ( ( rgbeStart[ 2 ] << 8 ) | rgbeStart[ 3 ] ) != scanline_width ) ) {
  179. return rgbe_error( rgbe_format_error, "bad rgbe scanline format" );
  180. }
  181. // read each of the four channels for the scanline into the buffer
  182. // first red, then green, then blue, then exponent
  183. ptr = 0;
  184. while ( ( ptr < ptr_end ) && ( pos < buffer.byteLength ) ) {
  185. count = buffer[ pos ++ ];
  186. isEncodedRun = count > 128;
  187. if ( isEncodedRun ) count -= 128;
  188. if ( ( 0 === count ) || ( ptr + count > ptr_end ) ) {
  189. return rgbe_error( rgbe_format_error, "bad scanline data" );
  190. }
  191. if ( isEncodedRun ) {
  192. // a (encoded) run of the same value
  193. byteValue = buffer[ pos ++ ];
  194. for ( i = 0; i < count; i ++ ) {
  195. scanline_buffer[ ptr ++ ] = byteValue;
  196. }
  197. //ptr += count;
  198. } else {
  199. // a literal-run
  200. scanline_buffer.set( buffer.subarray( pos, pos + count ), ptr );
  201. ptr += count; pos += count;
  202. }
  203. }
  204. // now convert data from buffer into rgba
  205. // first red, then green, then blue, then exponent (alpha)
  206. l = scanline_width; //scanline_buffer.byteLength;
  207. for ( i = 0; i < l; i ++ ) {
  208. off = 0;
  209. data_rgba[ offset ] = scanline_buffer[ i + off ];
  210. off += scanline_width; //1;
  211. data_rgba[ offset + 1 ] = scanline_buffer[ i + off ];
  212. off += scanline_width; //1;
  213. data_rgba[ offset + 2 ] = scanline_buffer[ i + off ];
  214. off += scanline_width; //1;
  215. data_rgba[ offset + 3 ] = scanline_buffer[ i + off ];
  216. offset += 4;
  217. }
  218. num_scanlines --;
  219. }
  220. return data_rgba;
  221. };
  222. var RGBEByteToRGBFloat = function ( sourceArray, sourceOffset, destArray, destOffset ) {
  223. var e = sourceArray[ sourceOffset + 3 ];
  224. var scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  225. destArray[ destOffset + 0 ] = sourceArray[ sourceOffset + 0 ] * scale;
  226. destArray[ destOffset + 1 ] = sourceArray[ sourceOffset + 1 ] * scale;
  227. destArray[ destOffset + 2 ] = sourceArray[ sourceOffset + 2 ] * scale;
  228. };
  229. var RGBEByteToRGBHalf = ( function () {
  230. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  231. var floatView = new Float32Array( 1 );
  232. var int32View = new Int32Array( floatView.buffer );
  233. /* This method is faster than the OpenEXR implementation (very often
  234. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  235. * by James Tursa?s half-precision code. */
  236. function toHalf( val ) {
  237. floatView[ 0 ] = val;
  238. var x = int32View[ 0 ];
  239. var bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  240. var m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  241. var e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  242. /* If zero, or denormal, or exponent underflows too much for a denormal
  243. * half, return signed zero. */
  244. if ( e < 103 ) return bits;
  245. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  246. if ( e > 142 ) {
  247. bits |= 0x7c00;
  248. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  249. * not Inf, so make sure we set one mantissa bit too. */
  250. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  251. return bits;
  252. }
  253. /* If exponent underflows but not too much, return a denormal */
  254. if ( e < 113 ) {
  255. m |= 0x0800;
  256. /* Extra rounding may overflow and set mantissa to 0 and exponent
  257. * to 1, which is OK. */
  258. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  259. return bits;
  260. }
  261. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  262. /* Extra rounding. An overflow will set mantissa to 0 and increment
  263. * the exponent, which is OK. */
  264. bits += m & 1;
  265. return bits;
  266. }
  267. return function ( sourceArray, sourceOffset, destArray, destOffset ) {
  268. var e = sourceArray[ sourceOffset + 3 ];
  269. var scale = Math.pow( 2.0, e - 128.0 ) / 255.0;
  270. destArray[ destOffset + 0 ] = toHalf( sourceArray[ sourceOffset + 0 ] * scale );
  271. destArray[ destOffset + 1 ] = toHalf( sourceArray[ sourceOffset + 1 ] * scale );
  272. destArray[ destOffset + 2 ] = toHalf( sourceArray[ sourceOffset + 2 ] * scale );
  273. };
  274. } )();
  275. var byteArray = new Uint8Array( buffer );
  276. byteArray.pos = 0;
  277. var rgbe_header_info = RGBE_ReadHeader( byteArray );
  278. if ( RGBE_RETURN_FAILURE !== rgbe_header_info ) {
  279. var w = rgbe_header_info.width,
  280. h = rgbe_header_info.height,
  281. image_rgba_data = RGBE_ReadPixels_RLE( byteArray.subarray( byteArray.pos ), w, h );
  282. if ( RGBE_RETURN_FAILURE !== image_rgba_data ) {
  283. switch ( this.type ) {
  284. case UnsignedByteType:
  285. var data = image_rgba_data;
  286. var format = RGBEFormat; // handled as THREE.RGBAFormat in shaders
  287. var type = UnsignedByteType;
  288. break;
  289. case FloatType:
  290. var numElements = ( image_rgba_data.length / 4 ) * 3;
  291. var floatArray = new Float32Array( numElements );
  292. for ( var j = 0; j < numElements; j ++ ) {
  293. RGBEByteToRGBFloat( image_rgba_data, j * 4, floatArray, j * 3 );
  294. }
  295. var data = floatArray;
  296. var format = RGBFormat;
  297. var type = FloatType;
  298. break;
  299. case HalfFloatType:
  300. var numElements = ( image_rgba_data.length / 4 ) * 3;
  301. var halfArray = new Uint16Array( numElements );
  302. for ( var j = 0; j < numElements; j ++ ) {
  303. RGBEByteToRGBHalf( image_rgba_data, j * 4, halfArray, j * 3 );
  304. }
  305. var data = halfArray;
  306. var format = RGBFormat;
  307. var type = HalfFloatType;
  308. break;
  309. default:
  310. console.error( 'THREE.RGBELoader: unsupported type: ', this.type );
  311. break;
  312. }
  313. return {
  314. width: w, height: h,
  315. data: data,
  316. header: rgbe_header_info.string,
  317. gamma: rgbe_header_info.gamma,
  318. exposure: rgbe_header_info.exposure,
  319. format: format,
  320. type: type
  321. };
  322. }
  323. }
  324. return null;
  325. },
  326. setDataType: function ( value ) {
  327. this.type = value;
  328. return this;
  329. },
  330. load: function ( url, onLoad, onProgress, onError ) {
  331. function onLoadCallback( texture, texData ) {
  332. switch ( texture.type ) {
  333. case UnsignedByteType:
  334. texture.encoding = RGBEEncoding;
  335. texture.minFilter = NearestFilter;
  336. texture.magFilter = NearestFilter;
  337. texture.generateMipmaps = false;
  338. texture.flipY = true;
  339. break;
  340. case FloatType:
  341. texture.encoding = LinearEncoding;
  342. texture.minFilter = LinearFilter;
  343. texture.magFilter = LinearFilter;
  344. texture.generateMipmaps = false;
  345. texture.flipY = true;
  346. break;
  347. case HalfFloatType:
  348. texture.encoding = LinearEncoding;
  349. texture.minFilter = LinearFilter;
  350. texture.magFilter = LinearFilter;
  351. texture.generateMipmaps = false;
  352. texture.flipY = true;
  353. break;
  354. }
  355. if ( onLoad ) onLoad( texture, texData );
  356. }
  357. return DataTextureLoader.prototype.load.call( this, url, onLoadCallback, onProgress, onError );
  358. }
  359. } );
  360. export { RGBELoader };