NRRDLoader.js 13 KB

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