RGBELoader.js 12 KB

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