RGBELoader.js 12 KB

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