RGBELoader.js 12 KB

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