NRRDLoader.js 12 KB

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