NRRDLoader.js 13 KB

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