RGBELoader.js 14 KB

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