RGBELoader.js 14 KB

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