RGBELoader.js 11 KB

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