RGBELoader.js 12 KB

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