NRRDLoader.js 12 KB

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