NRRDLoader.js 12 KB

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