NRRDLoader.js 13 KB

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