RGBELoader.js 12 KB

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