NRRDLoader.js 12 KB

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