NRRDLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 ) );
  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( _spaceX, 0, 0, 0,
  244. 0, _spaceY, 0, 0,
  245. 0, 0, _spaceZ, 0,
  246. 0, 0, 0, 1 );
  247. } else {
  248. var v = headerObject.vectors;
  249. var origin = headerObject.space_origin;
  250. if ( ! origin ) {
  251. origin = [ 0, 0, 0 ];
  252. }
  253. volume.matrix.set( _spaceX * v[ 0 ][ 0 ], _spaceX * v[ 1 ][ 0 ], _spaceX * v[ 2 ][ 0 ], 0,
  254. _spaceY * v[ 0 ][ 1 ], _spaceY * v[ 1 ][ 1 ], _spaceY * v[ 2 ][ 1 ], 0,
  255. _spaceZ * v[ 0 ][ 2 ], _spaceZ * v[ 1 ][ 2 ], _spaceZ * v[ 2 ][ 2 ], 0,
  256. 0, 0, 0, 1 );
  257. }
  258. volume.inverseMatrix = new THREE.Matrix4();
  259. volume.inverseMatrix.getInverse( volume.matrix );
  260. volume.RASDimensions = ( new THREE.Vector3( volume.xLength, volume.yLength, volume.zLength ) ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  261. // .. and set the default threshold
  262. // only if the threshold was not already set
  263. if ( volume.lowerThreshold === - Infinity ) {
  264. volume.lowerThreshold = min;
  265. }
  266. if ( volume.upperThreshold === Infinity ) {
  267. volume.upperThreshold = max;
  268. }
  269. return volume;
  270. },
  271. parseChars: function ( array, start, end ) {
  272. // without borders, use the whole array
  273. if ( start === undefined ) {
  274. start = 0;
  275. }
  276. if ( end === undefined ) {
  277. end = array.length;
  278. }
  279. var output = '';
  280. // create and append the chars
  281. var i = 0;
  282. for ( i = start; i < end; ++ i ) {
  283. output += String.fromCharCode( array[ i ] );
  284. }
  285. return output;
  286. },
  287. fieldFunctions: {
  288. type: function ( data ) {
  289. switch ( data ) {
  290. case 'uchar':
  291. case 'unsigned char':
  292. case 'uint8':
  293. case 'uint8_t':
  294. this.__array = Uint8Array;
  295. break;
  296. case 'signed char':
  297. case 'int8':
  298. case 'int8_t':
  299. this.__array = Int8Array;
  300. break;
  301. case 'short':
  302. case 'short int':
  303. case 'signed short':
  304. case 'signed short int':
  305. case 'int16':
  306. case 'int16_t':
  307. this.__array = Int16Array;
  308. break;
  309. case 'ushort':
  310. case 'unsigned short':
  311. case 'unsigned short int':
  312. case 'uint16':
  313. case 'uint16_t':
  314. this.__array = Uint16Array;
  315. break;
  316. case 'int':
  317. case 'signed int':
  318. case 'int32':
  319. case 'int32_t':
  320. this.__array = Int32Array;
  321. break;
  322. case 'uint':
  323. case 'unsigned int':
  324. case 'uint32':
  325. case 'uint32_t':
  326. this.__array = Uint32Array;
  327. break;
  328. case 'float':
  329. this.__array = Float32Array;
  330. break;
  331. case 'double':
  332. this.__array = Float64Array;
  333. break;
  334. default:
  335. throw new Error( 'Unsupported NRRD data type: ' + data );
  336. }
  337. return this.type = data;
  338. },
  339. endian: function ( data ) {
  340. return this.endian = data;
  341. },
  342. encoding: function ( data ) {
  343. return this.encoding = data;
  344. },
  345. dimension: function ( data ) {
  346. return this.dim = parseInt( data, 10 );
  347. },
  348. sizes: function ( data ) {
  349. var i;
  350. return this.sizes = ( function () {
  351. var _i, _len, _ref, _results;
  352. _ref = data.split( /\s+/ );
  353. _results = [];
  354. for ( _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  355. i = _ref[ _i ];
  356. _results.push( parseInt( i, 10 ) );
  357. }
  358. return _results;
  359. } )();
  360. },
  361. space: function ( data ) {
  362. return this.space = data;
  363. },
  364. 'space origin': function ( data ) {
  365. return this.space_origin = data.split( "(" )[ 1 ].split( ")" )[ 0 ].split( "," );
  366. },
  367. 'space directions': function ( data ) {
  368. var f, parts, v;
  369. parts = data.match( /\(.*?\)/g );
  370. return this.vectors = ( function () {
  371. var _i, _len, _results;
  372. _results = [];
  373. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  374. v = parts[ _i ];
  375. _results.push( ( function () {
  376. var _j, _len2, _ref, _results2;
  377. _ref = v.slice( 1, - 1 ).split( /,/ );
  378. _results2 = [];
  379. for ( _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  380. f = _ref[ _j ];
  381. _results2.push( parseFloat( f ) );
  382. }
  383. return _results2;
  384. } )() );
  385. }
  386. return _results;
  387. } )();
  388. },
  389. spacings: function ( data ) {
  390. var f, parts;
  391. parts = data.split( /\s+/ );
  392. return this.spacings = ( function () {
  393. var _i, _len, _results = [];
  394. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  395. f = parts[ _i ];
  396. _results.push( parseFloat( f ) );
  397. }
  398. return _results;
  399. } )();
  400. }
  401. }
  402. };