NRRDLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. // .. let's use the underlying array buffer
  201. _data = _data.buffer;
  202. var volume = new THREE.Volume();
  203. volume.header = headerObject;
  204. //
  205. // parse the (unzipped) data to a datastream of the correct type
  206. //
  207. volume.data = new headerObject.__array( _data );
  208. // get the min and max intensities
  209. var min_max = volume.computeMinMax();
  210. var min = min_max[ 0 ];
  211. var max = min_max[ 1 ];
  212. // attach the scalar range to the volume
  213. volume.windowLow = min;
  214. volume.windowHigh = max;
  215. // get the image dimensions
  216. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  217. volume.xLength = volume.dimensions[ 0 ];
  218. volume.yLength = volume.dimensions[ 1 ];
  219. volume.zLength = volume.dimensions[ 2 ];
  220. // spacing
  221. var spacingX = ( new THREE.Vector3( headerObject.vectors[ 0 ][ 0 ], headerObject.vectors[ 0 ][ 1 ],
  222. headerObject.vectors[ 0 ][ 2 ] ) ).length();
  223. var spacingY = ( new THREE.Vector3( headerObject.vectors[ 1 ][ 0 ], headerObject.vectors[ 1 ][ 1 ],
  224. headerObject.vectors[ 1 ][ 2 ] ) ).length();
  225. var spacingZ = ( new THREE.Vector3( headerObject.vectors[ 2 ][ 0 ], headerObject.vectors[ 2 ][ 1 ],
  226. headerObject.vectors[ 2 ][ 2 ] ) ).length();
  227. volume.spacing = [ spacingX, spacingY, spacingZ ];
  228. // Create IJKtoRAS matrix
  229. volume.matrix = new THREE.Matrix4();
  230. var _spaceX = 1;
  231. var _spaceY = 1;
  232. var _spaceZ = 1;
  233. if ( headerObject.space == "left-posterior-superior" ) {
  234. _spaceX = - 1;
  235. _spaceY = - 1;
  236. }
  237. else if ( headerObject.space === 'left-anterior-superior' ) {
  238. _spaceX = - 1
  239. }
  240. if ( ! headerObject.vectors ) {
  241. volume.matrix.set( _spaceX, 0, 0, 0,
  242. 0, _spaceY, 0, 0,
  243. 0, 0, _spaceZ, 0,
  244. 0, 0, 0, 1 );
  245. }
  246. else {
  247. var v = headerObject.vectors;
  248. var origin = headerObject.space_origin;
  249. if ( ! origin ) {
  250. origin = [ 0, 0, 0 ];
  251. }
  252. volume.matrix.set( _spaceX * v[ 0 ][ 0 ], _spaceX * v[ 1 ][ 0 ], _spaceX * v[ 2 ][ 0 ], 0,
  253. _spaceY * v[ 0 ][ 1 ], _spaceY * v[ 1 ][ 1 ], _spaceY * v[ 2 ][ 1 ], 0,
  254. _spaceZ * v[ 0 ][ 2 ], _spaceZ * v[ 1 ][ 2 ], _spaceZ * v[ 2 ][ 2 ], 0,
  255. 0, 0, 0, 1 );
  256. }
  257. volume.inverseMatrix = new THREE.Matrix4();
  258. volume.inverseMatrix.getInverse( volume.matrix );
  259. volume.RASDimensions = ( new THREE.Vector3( volume.xLength, volume.yLength, volume.zLength ) ).applyMatrix4( volume.matrix ).round().toArray().map( Math.abs );
  260. // .. and set the default threshold
  261. // only if the threshold was not already set
  262. if ( volume.lowerThreshold === - Infinity ) {
  263. volume.lowerThreshold = min;
  264. }
  265. if ( volume.upperThreshold === Infinity ) {
  266. volume.upperThreshold = max;
  267. }
  268. return volume;
  269. },
  270. parseChars: function( array, start, end ) {
  271. // without borders, use the whole array
  272. if ( start === undefined ) {
  273. start = 0;
  274. }
  275. if ( end === undefined ) {
  276. end = array.length;
  277. }
  278. var output = '';
  279. // create and append the chars
  280. var i = 0;
  281. for ( i = start; i < end; ++ i ) {
  282. output += String.fromCharCode( array[ i ] );
  283. }
  284. return output;
  285. },
  286. fieldFunctions: {
  287. type: function( data ) {
  288. switch ( data ) {
  289. case 'uchar':
  290. case 'unsigned char':
  291. case 'uint8':
  292. case 'uint8_t':
  293. this.__array = Uint8Array;
  294. break;
  295. case 'signed char':
  296. case 'int8':
  297. case 'int8_t':
  298. this.__array = Int8Array;
  299. break;
  300. case 'short':
  301. case 'short int':
  302. case 'signed short':
  303. case 'signed short int':
  304. case 'int16':
  305. case 'int16_t':
  306. this.__array = Int16Array;
  307. break;
  308. case 'ushort':
  309. case 'unsigned short':
  310. case 'unsigned short int':
  311. case 'uint16':
  312. case 'uint16_t':
  313. this.__array = Uint16Array;
  314. break;
  315. case 'int':
  316. case 'signed int':
  317. case 'int32':
  318. case 'int32_t':
  319. this.__array = Int32Array;
  320. break;
  321. case 'uint':
  322. case 'unsigned int':
  323. case 'uint32':
  324. case 'uint32_t':
  325. this.__array = Uint32Array;
  326. break;
  327. case 'float':
  328. this.__array = Float32Array;
  329. break;
  330. case 'double':
  331. this.__array = Float64Array;
  332. break;
  333. default:
  334. throw new Error( 'Unsupported NRRD data type: ' + data );
  335. }
  336. return this.type = data;
  337. },
  338. endian: function( data ) {
  339. return this.endian = data;
  340. },
  341. encoding: function( data ) {
  342. return this.encoding = data;
  343. },
  344. dimension: function( data ) {
  345. return this.dim = parseInt( data, 10 );
  346. },
  347. sizes: function( data ) {
  348. var i;
  349. return this.sizes = ( function() {
  350. var _i, _len, _ref, _results;
  351. _ref = data.split( /\s+/ );
  352. _results = [];
  353. for ( _i = 0, _len = _ref.length; _i < _len; _i ++ ) {
  354. i = _ref[ _i ];
  355. _results.push( parseInt( i, 10 ) );
  356. }
  357. return _results;
  358. } )();
  359. },
  360. space: function( data ) {
  361. return this.space = data;
  362. },
  363. 'space origin' : function( data ) {
  364. return this.space_origin = data.split( "(" )[ 1 ].split( ")" )[ 0 ].split( "," );
  365. },
  366. 'space directions' : function( data ) {
  367. var f, parts, v;
  368. parts = data.match( /\(.*?\)/g );
  369. return this.vectors = ( function() {
  370. var _i, _len, _results;
  371. _results = [];
  372. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  373. v = parts[ _i ];
  374. _results.push( ( function() {
  375. var _j, _len2, _ref, _results2;
  376. _ref = v.slice( 1, - 1 ).split( /,/ );
  377. _results2 = [];
  378. for ( _j = 0, _len2 = _ref.length; _j < _len2; _j ++ ) {
  379. f = _ref[ _j ];
  380. _results2.push( parseFloat( f ) );
  381. }
  382. return _results2;
  383. } )() );
  384. }
  385. return _results;
  386. } )();
  387. },
  388. spacings: function( data ) {
  389. var f, parts;
  390. parts = data.split( /\s+/ );
  391. return this.spacings = ( function() {
  392. var _i, _len, _results;
  393. _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. } );