RGBELoader.js 12 KB

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