NRRDLoader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. volume.segmentation = this.segmentation;
  237. //
  238. // parse the (unzipped) data to a datastream of the correct type
  239. //
  240. volume.data = new headerObject.__array( _data );
  241. // get the min and max intensities
  242. const min_max = volume.computeMinMax();
  243. const min = min_max[ 0 ];
  244. const max = min_max[ 1 ];
  245. // attach the scalar range to the volume
  246. volume.windowLow = min;
  247. volume.windowHigh = max;
  248. // get the image dimensions
  249. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  250. volume.xLength = volume.dimensions[ 0 ];
  251. volume.yLength = volume.dimensions[ 1 ];
  252. volume.zLength = volume.dimensions[ 2 ];
  253. // Identify axis order in the space-directions matrix from the header if possible.
  254. if ( headerObject.vectors ) {
  255. const xIndex = headerObject.vectors.findIndex( vector => vector[ 0 ] !== 0 );
  256. const yIndex = headerObject.vectors.findIndex( vector => vector[ 1 ] !== 0 );
  257. const zIndex = headerObject.vectors.findIndex( vector => vector[ 2 ] !== 0 );
  258. const axisOrder = [];
  259. if ( xIndex !== yIndex && xIndex !== zIndex && yIndex !== zIndex ) {
  260. axisOrder[ xIndex ] = 'x';
  261. axisOrder[ yIndex ] = 'y';
  262. axisOrder[ zIndex ] = 'z';
  263. } else {
  264. axisOrder[ 0 ] = 'x';
  265. axisOrder[ 1 ] = 'y';
  266. axisOrder[ 2 ] = 'z';
  267. }
  268. volume.axisOrder = axisOrder;
  269. } else {
  270. volume.axisOrder = [ 'x', 'y', 'z' ];
  271. }
  272. // spacing
  273. const spacingX = new Vector3().fromArray( headerObject.vectors[ 0 ] ).length();
  274. const spacingY = new Vector3().fromArray( headerObject.vectors[ 1 ] ).length();
  275. const spacingZ = new Vector3().fromArray( headerObject.vectors[ 2 ] ).length();
  276. volume.spacing = [ spacingX, spacingY, spacingZ ];
  277. // Create IJKtoRAS matrix
  278. volume.matrix = new Matrix4();
  279. const transitionMatrix = new Matrix4();
  280. if ( headerObject.space === 'left-posterior-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. } else if ( headerObject.space === 'left-anterior-superior' ) {
  288. transitionMatrix.set(
  289. 1, 0, 0, 0,
  290. 0, 1, 0, 0,
  291. 0, 0, - 1, 0,
  292. 0, 0, 0, 1
  293. );
  294. }
  295. if ( ! headerObject.vectors ) {
  296. volume.matrix.set(
  297. 1, 0, 0, 0,
  298. 0, 1, 0, 0,
  299. 0, 0, 1, 0,
  300. 0, 0, 0, 1 );
  301. } else {
  302. const v = headerObject.vectors;
  303. const ijk_to_transition = new Matrix4().set(
  304. v[ 0 ][ 0 ], v[ 1 ][ 0 ], v[ 2 ][ 0 ], 0,
  305. v[ 0 ][ 1 ], v[ 1 ][ 1 ], v[ 2 ][ 1 ], 0,
  306. v[ 0 ][ 2 ], v[ 1 ][ 2 ], v[ 2 ][ 2 ], 0,
  307. 0, 0, 0, 1
  308. );
  309. const transition_to_ras = new Matrix4().multiplyMatrices( ijk_to_transition, transitionMatrix );
  310. volume.matrix = transition_to_ras;
  311. }
  312. volume.inverseMatrix = new Matrix4();
  313. volume.inverseMatrix.copy( volume.matrix ).invert();
  314. volume.RASDimensions = [
  315. Math.floor( volume.xLength * spacingX ),
  316. Math.floor( volume.yLength * spacingY ),
  317. Math.floor( volume.zLength * spacingZ )
  318. ];
  319. // .. and set the default threshold
  320. // only if the threshold was not already set
  321. if ( volume.lowerThreshold === - Infinity ) {
  322. volume.lowerThreshold = min;
  323. }
  324. if ( volume.upperThreshold === Infinity ) {
  325. volume.upperThreshold = max;
  326. }
  327. return volume;
  328. }
  329. parseChars( array, start, end ) {
  330. // without borders, use the whole array
  331. if ( start === undefined ) {
  332. start = 0;
  333. }
  334. if ( end === undefined ) {
  335. end = array.length;
  336. }
  337. let output = '';
  338. // create and append the chars
  339. let i = 0;
  340. for ( i = start; i < end; ++ i ) {
  341. output += String.fromCharCode( array[ i ] );
  342. }
  343. return output;
  344. }
  345. }
  346. const _fieldFunctions = {
  347. type: function ( data ) {
  348. switch ( data ) {
  349. case 'uchar':
  350. case 'unsigned char':
  351. case 'uint8':
  352. case 'uint8_t':
  353. this.__array = Uint8Array;
  354. break;
  355. case 'signed char':
  356. case 'int8':
  357. case 'int8_t':
  358. this.__array = Int8Array;
  359. break;
  360. case 'short':
  361. case 'short int':
  362. case 'signed short':
  363. case 'signed short int':
  364. case 'int16':
  365. case 'int16_t':
  366. this.__array = Int16Array;
  367. break;
  368. case 'ushort':
  369. case 'unsigned short':
  370. case 'unsigned short int':
  371. case 'uint16':
  372. case 'uint16_t':
  373. this.__array = Uint16Array;
  374. break;
  375. case 'int':
  376. case 'signed int':
  377. case 'int32':
  378. case 'int32_t':
  379. this.__array = Int32Array;
  380. break;
  381. case 'uint':
  382. case 'unsigned int':
  383. case 'uint32':
  384. case 'uint32_t':
  385. this.__array = Uint32Array;
  386. break;
  387. case 'float':
  388. this.__array = Float32Array;
  389. break;
  390. case 'double':
  391. this.__array = Float64Array;
  392. break;
  393. default:
  394. throw new Error( 'Unsupported NRRD data type: ' + data );
  395. }
  396. return this.type = data;
  397. },
  398. endian: function ( data ) {
  399. return this.endian = data;
  400. },
  401. encoding: function ( data ) {
  402. return this.encoding = data;
  403. },
  404. dimension: function ( data ) {
  405. return this.dim = parseInt( data, 10 );
  406. },
  407. sizes: function ( data ) {
  408. let i;
  409. return this.sizes = ( function () {
  410. const _ref = data.split( /\s+/ );
  411. const _results = [];
  412. for ( let _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  413. i = _ref[ _i ];
  414. _results.push( parseInt( i, 10 ) );
  415. }
  416. return _results;
  417. } )();
  418. },
  419. space: function ( data ) {
  420. return this.space = data;
  421. },
  422. 'space origin': function ( data ) {
  423. return this.space_origin = data.split( '(' )[ 1 ].split( ')' )[ 0 ].split( ',' );
  424. },
  425. 'space directions': function ( data ) {
  426. let f, v;
  427. const parts = data.match( /\(.*?\)/g );
  428. return this.vectors = ( function () {
  429. const _results = [];
  430. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  431. v = parts[ _i ];
  432. _results.push( ( function () {
  433. const _ref = v.slice( 1, - 1 ).split( /,/ );
  434. const _results2 = [];
  435. for ( let _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  436. f = _ref[ _j ];
  437. _results2.push( parseFloat( f ) );
  438. }
  439. return _results2;
  440. } )() );
  441. }
  442. return _results;
  443. } )();
  444. },
  445. spacings: function ( data ) {
  446. let f;
  447. const parts = data.split( /\s+/ );
  448. return this.spacings = ( function () {
  449. const _results = [];
  450. for ( let _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  451. f = parts[ _i ];
  452. _results.push( parseFloat( f ) );
  453. }
  454. return _results;
  455. } )();
  456. }
  457. };
  458. export { NRRDLoader };