2
0

NRRDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import {
  2. FileLoader,
  3. Loader,
  4. Matrix4,
  5. Vector3
  6. } from '../../../build/three.module.js';
  7. import * as fflate from '../libs/fflate.module.min.js';
  8. import { Volume } from '../misc/Volume.js';
  9. var NRRDLoader = function ( manager ) {
  10. Loader.call( this, manager );
  11. };
  12. NRRDLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  13. constructor: NRRDLoader,
  14. load: function ( url, onLoad, onProgress, onError ) {
  15. var scope = this;
  16. var loader = new FileLoader( scope.manager );
  17. loader.setPath( scope.path );
  18. loader.setResponseType( 'arraybuffer' );
  19. loader.setRequestHeader( scope.requestHeader );
  20. loader.setWithCredentials( scope.withCredentials );
  21. loader.load( url, function ( data ) {
  22. try {
  23. onLoad( scope.parse( data ) );
  24. } catch ( e ) {
  25. if ( onError ) {
  26. onError( e );
  27. } else {
  28. console.error( e );
  29. }
  30. scope.manager.itemError( url );
  31. }
  32. }, onProgress, onError );
  33. },
  34. parse: function ( data ) {
  35. // this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  36. var _data = data;
  37. var _dataPointer = 0;
  38. var _nativeLittleEndian = new Int8Array( new Int16Array( [ 1 ] ).buffer )[ 0 ] > 0;
  39. var _littleEndian = true;
  40. var headerObject = {};
  41. function scan( type, chunks ) {
  42. if ( chunks === undefined || chunks === null ) {
  43. chunks = 1;
  44. }
  45. var _chunkSize = 1;
  46. var _array_type = Uint8Array;
  47. switch ( type ) {
  48. // 1 byte data types
  49. case 'uchar':
  50. break;
  51. case 'schar':
  52. _array_type = Int8Array;
  53. break;
  54. // 2 byte data types
  55. case 'ushort':
  56. _array_type = Uint16Array;
  57. _chunkSize = 2;
  58. break;
  59. case 'sshort':
  60. _array_type = Int16Array;
  61. _chunkSize = 2;
  62. break;
  63. // 4 byte data types
  64. case 'uint':
  65. _array_type = Uint32Array;
  66. _chunkSize = 4;
  67. break;
  68. case 'sint':
  69. _array_type = Int32Array;
  70. _chunkSize = 4;
  71. break;
  72. case 'float':
  73. _array_type = Float32Array;
  74. _chunkSize = 4;
  75. break;
  76. case 'complex':
  77. _array_type = Float64Array;
  78. _chunkSize = 8;
  79. break;
  80. case 'double':
  81. _array_type = Float64Array;
  82. _chunkSize = 8;
  83. break;
  84. }
  85. // increase the data pointer in-place
  86. var _bytes = new _array_type( _data.slice( _dataPointer,
  87. _dataPointer += chunks * _chunkSize ) );
  88. // if required, flip the endianness of the bytes
  89. if ( _nativeLittleEndian != _littleEndian ) {
  90. // we need to flip here since the format doesn't match the native endianness
  91. _bytes = flipEndianness( _bytes, _chunkSize );
  92. }
  93. if ( chunks == 1 ) {
  94. // if only one chunk was requested, just return one value
  95. return _bytes[ 0 ];
  96. }
  97. // return the byte array
  98. return _bytes;
  99. }
  100. //Flips typed array endianness in-place. Based on https://github.com/kig/DataStream.js/blob/master/DataStream.js.
  101. function flipEndianness( array, chunkSize ) {
  102. var u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  103. for ( var i = 0; i < array.byteLength; i += chunkSize ) {
  104. for ( var j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  105. var tmp = u8[ k ];
  106. u8[ k ] = u8[ j ];
  107. u8[ j ] = tmp;
  108. }
  109. }
  110. return array;
  111. }
  112. //parse the header
  113. function parseHeader( header ) {
  114. var data, field, fn, i, l, lines, m, _i, _len;
  115. lines = header.split( /\r?\n/ );
  116. for ( _i = 0, _len = lines.length; _i < _len; _i ++ ) {
  117. l = lines[ _i ];
  118. if ( l.match( /NRRD\d+/ ) ) {
  119. headerObject.isNrrd = true;
  120. } else if ( l.match( /^#/ ) ) {
  121. } else if ( m = l.match( /(.*):(.*)/ ) ) {
  122. field = m[ 1 ].trim();
  123. data = m[ 2 ].trim();
  124. fn = NRRDLoader.prototype.fieldFunctions[ field ];
  125. if ( fn ) {
  126. fn.call( headerObject, data );
  127. } else {
  128. headerObject[ field ] = data;
  129. }
  130. }
  131. }
  132. if ( ! headerObject.isNrrd ) {
  133. throw new Error( 'Not an NRRD file' );
  134. }
  135. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  136. throw new Error( 'Bzip is not supported' );
  137. }
  138. if ( ! headerObject.vectors ) {
  139. //if no space direction is set, let's use the identity
  140. headerObject.vectors = [ new Vector3( 1, 0, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ) ];
  141. //apply spacing if defined
  142. if ( headerObject.spacings ) {
  143. for ( i = 0; i <= 2; i ++ ) {
  144. if ( ! isNaN( headerObject.spacings[ i ] ) ) {
  145. headerObject.vectors[ i ].multiplyScalar( headerObject.spacings[ i ] );
  146. }
  147. }
  148. }
  149. }
  150. }
  151. //parse the data when registred as one of this type : 'text', 'ascii', 'txt'
  152. function parseDataAsText( data, start, end ) {
  153. var number = '';
  154. start = start || 0;
  155. end = end || data.length;
  156. var value;
  157. //length of the result is the product of the sizes
  158. var lengthOfTheResult = headerObject.sizes.reduce( function ( previous, current ) {
  159. return previous * current;
  160. }, 1 );
  161. var base = 10;
  162. if ( headerObject.encoding === 'hex' ) {
  163. base = 16;
  164. }
  165. var result = new headerObject.__array( lengthOfTheResult );
  166. var resultIndex = 0;
  167. var parsingFunction = parseInt;
  168. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  169. parsingFunction = parseFloat;
  170. }
  171. for ( var i = start; i < end; i ++ ) {
  172. value = data[ i ];
  173. //if value is not a space
  174. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  175. number += String.fromCharCode( value );
  176. } else {
  177. if ( number !== '' ) {
  178. result[ resultIndex ] = parsingFunction( number, base );
  179. resultIndex ++;
  180. }
  181. number = '';
  182. }
  183. }
  184. if ( number !== '' ) {
  185. result[ resultIndex ] = parsingFunction( number, base );
  186. resultIndex ++;
  187. }
  188. return result;
  189. }
  190. var _bytes = scan( 'uchar', data.byteLength );
  191. var _length = _bytes.length;
  192. var _header = null;
  193. var _data_start = 0;
  194. var i;
  195. for ( i = 1; i < _length; i ++ ) {
  196. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  197. // we found two line breaks in a row
  198. // now we know what the header is
  199. _header = this.parseChars( _bytes, 0, i - 2 );
  200. // this is were the data starts
  201. _data_start = i + 1;
  202. break;
  203. }
  204. }
  205. // parse the header
  206. parseHeader( _header );
  207. var _data = _bytes.subarray( _data_start ); // the data without header
  208. if ( headerObject.encoding.substring( 0, 2 ) === 'gz' ) {
  209. // we need to decompress the datastream
  210. // here we start the unzipping and get a typed Uint8Array back
  211. _data = fflate.gunzipSync( new Uint8Array( _data ) );// eslint-disable-line no-undef
  212. } else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  213. _data = parseDataAsText( _data );
  214. } else if ( headerObject.encoding === 'raw' ) {
  215. //we need to copy the array to create a new array buffer, else we retrieve the original arraybuffer with the header
  216. var _copy = new Uint8Array( _data.length );
  217. for ( var i = 0; i < _data.length; i ++ ) {
  218. _copy[ i ] = _data[ i ];
  219. }
  220. _data = _copy;
  221. }
  222. // .. let's use the underlying array buffer
  223. _data = _data.buffer;
  224. var volume = new Volume();
  225. volume.header = headerObject;
  226. //
  227. // parse the (unzipped) data to a datastream of the correct type
  228. //
  229. volume.data = new headerObject.__array( _data );
  230. // get the min and max intensities
  231. var min_max = volume.computeMinMax();
  232. var min = min_max[ 0 ];
  233. var max = min_max[ 1 ];
  234. // attach the scalar range to the volume
  235. volume.windowLow = min;
  236. volume.windowHigh = max;
  237. // get the image dimensions
  238. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  239. volume.xLength = volume.dimensions[ 0 ];
  240. volume.yLength = volume.dimensions[ 1 ];
  241. volume.zLength = volume.dimensions[ 2 ];
  242. // spacing
  243. var spacingX = ( new Vector3( headerObject.vectors[ 0 ][ 0 ], headerObject.vectors[ 0 ][ 1 ],
  244. headerObject.vectors[ 0 ][ 2 ] ) ).length();
  245. var spacingY = ( new Vector3( headerObject.vectors[ 1 ][ 0 ], headerObject.vectors[ 1 ][ 1 ],
  246. headerObject.vectors[ 1 ][ 2 ] ) ).length();
  247. var spacingZ = ( new Vector3( headerObject.vectors[ 2 ][ 0 ], headerObject.vectors[ 2 ][ 1 ],
  248. headerObject.vectors[ 2 ][ 2 ] ) ).length();
  249. volume.spacing = [ spacingX, spacingY, spacingZ ];
  250. // Create IJKtoRAS matrix
  251. volume.matrix = new Matrix4();
  252. var _spaceX = 1;
  253. var _spaceY = 1;
  254. var _spaceZ = 1;
  255. if ( headerObject.space == 'left-posterior-superior' ) {
  256. _spaceX = - 1;
  257. _spaceY = - 1;
  258. } else if ( headerObject.space === 'left-anterior-superior' ) {
  259. _spaceX = - 1;
  260. }
  261. if ( ! headerObject.vectors ) {
  262. volume.matrix.set(
  263. _spaceX, 0, 0, 0,
  264. 0, _spaceY, 0, 0,
  265. 0, 0, _spaceZ, 0,
  266. 0, 0, 0, 1 );
  267. } else {
  268. var v = headerObject.vectors;
  269. volume.matrix.set(
  270. _spaceX * v[ 0 ][ 0 ], _spaceX * v[ 1 ][ 0 ], _spaceX * v[ 2 ][ 0 ], 0,
  271. _spaceY * v[ 0 ][ 1 ], _spaceY * v[ 1 ][ 1 ], _spaceY * v[ 2 ][ 1 ], 0,
  272. _spaceZ * v[ 0 ][ 2 ], _spaceZ * v[ 1 ][ 2 ], _spaceZ * v[ 2 ][ 2 ], 0,
  273. 0, 0, 0, 1 );
  274. }
  275. volume.inverseMatrix = new Matrix4();
  276. volume.inverseMatrix.copy( volume.matrix ).invert();
  277. volume.RASDimensions = ( new Vector3( volume.xLength, volume.yLength, volume.zLength ) ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  278. // .. and set the default threshold
  279. // only if the threshold was not already set
  280. if ( volume.lowerThreshold === - Infinity ) {
  281. volume.lowerThreshold = min;
  282. }
  283. if ( volume.upperThreshold === Infinity ) {
  284. volume.upperThreshold = max;
  285. }
  286. return volume;
  287. },
  288. parseChars: function ( array, start, end ) {
  289. // without borders, use the whole array
  290. if ( start === undefined ) {
  291. start = 0;
  292. }
  293. if ( end === undefined ) {
  294. end = array.length;
  295. }
  296. var output = '';
  297. // create and append the chars
  298. var i = 0;
  299. for ( i = start; i < end; ++ i ) {
  300. output += String.fromCharCode( array[ i ] );
  301. }
  302. return output;
  303. },
  304. fieldFunctions: {
  305. type: function ( data ) {
  306. switch ( data ) {
  307. case 'uchar':
  308. case 'unsigned char':
  309. case 'uint8':
  310. case 'uint8_t':
  311. this.__array = Uint8Array;
  312. break;
  313. case 'signed char':
  314. case 'int8':
  315. case 'int8_t':
  316. this.__array = Int8Array;
  317. break;
  318. case 'short':
  319. case 'short int':
  320. case 'signed short':
  321. case 'signed short int':
  322. case 'int16':
  323. case 'int16_t':
  324. this.__array = Int16Array;
  325. break;
  326. case 'ushort':
  327. case 'unsigned short':
  328. case 'unsigned short int':
  329. case 'uint16':
  330. case 'uint16_t':
  331. this.__array = Uint16Array;
  332. break;
  333. case 'int':
  334. case 'signed int':
  335. case 'int32':
  336. case 'int32_t':
  337. this.__array = Int32Array;
  338. break;
  339. case 'uint':
  340. case 'unsigned int':
  341. case 'uint32':
  342. case 'uint32_t':
  343. this.__array = Uint32Array;
  344. break;
  345. case 'float':
  346. this.__array = Float32Array;
  347. break;
  348. case 'double':
  349. this.__array = Float64Array;
  350. break;
  351. default:
  352. throw new Error( 'Unsupported NRRD data type: ' + data );
  353. }
  354. return this.type = data;
  355. },
  356. endian: function ( data ) {
  357. return this.endian = data;
  358. },
  359. encoding: function ( data ) {
  360. return this.encoding = data;
  361. },
  362. dimension: function ( data ) {
  363. return this.dim = parseInt( data, 10 );
  364. },
  365. sizes: function ( data ) {
  366. var i;
  367. return this.sizes = ( function () {
  368. var _i, _len, _ref, _results;
  369. _ref = data.split( /\s+/ );
  370. _results = [];
  371. for ( _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  372. i = _ref[ _i ];
  373. _results.push( parseInt( i, 10 ) );
  374. }
  375. return _results;
  376. } )();
  377. },
  378. space: function ( data ) {
  379. return this.space = data;
  380. },
  381. 'space origin': function ( data ) {
  382. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  383. },
  384. 'space directions': function ( data ) {
  385. var f, parts, v;
  386. parts = data.match( /\(.*?\)/g );
  387. return this.vectors = ( function () {
  388. var _i, _len, _results;
  389. _results = [];
  390. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  391. v = parts[ _i ];
  392. _results.push( ( function () {
  393. var _j, _len2, _ref, _results2;
  394. _ref = v.slice( 1, - 1 ).split( /,/ );
  395. _results2 = [];
  396. for ( _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  397. f = _ref[ _j ];
  398. _results2.push( parseFloat( f ) );
  399. }
  400. return _results2;
  401. } )() );
  402. }
  403. return _results;
  404. } )();
  405. },
  406. spacings: function ( data ) {
  407. var f, parts;
  408. parts = data.split( /\s+/ );
  409. return this.spacings = ( function () {
  410. var _i, _len, _results = [];
  411. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  412. f = parts[ _i ];
  413. _results.push( parseFloat( f ) );
  414. }
  415. return _results;
  416. } )();
  417. }
  418. }
  419. } );
  420. export { NRRDLoader };