NRRDLoader.js 13 KB

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