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.XHRLoader( scope.manager );
  9. loader.setResponseType( 'arraybuffer' );
  10. loader.load( url, function( data ) {
  11. onLoad( scope.parse( data ) );
  12. }, onProgress, onError );
  13. },
  14. //this parser is largely inspired from the XTK NRRD parser : https://github.com/xtk/X
  15. parse: function( data ) {
  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 _lastMin = - Infinity;
  21. var _lastMax = Infinity;
  22. var headerObject = {};
  23. function scan( type, chunks ) {
  24. if ( chunks === undefined || chunks === null ) {
  25. chunks = 1;
  26. }
  27. var _chunkSize = 1;
  28. var _array_type = Uint8Array;
  29. switch ( type ) {
  30. // 1 byte data types
  31. case 'uchar':
  32. break;
  33. case 'schar':
  34. _array_type = Int8Array;
  35. break;
  36. // 2 byte data types
  37. case 'ushort':
  38. _array_type = Uint16Array;
  39. _chunkSize = 2;
  40. break;
  41. case 'sshort':
  42. _array_type = Int16Array;
  43. _chunkSize = 2;
  44. break;
  45. // 4 byte data types
  46. case 'uint':
  47. _array_type = Uint32Array;
  48. _chunkSize = 4;
  49. break;
  50. case 'sint':
  51. _array_type = Int32Array;
  52. _chunkSize = 4;
  53. break;
  54. case 'float':
  55. _array_type = Float32Array;
  56. _chunkSize = 4;
  57. break;
  58. case 'complex':
  59. _array_type = Float64Array;
  60. _chunkSize = 8;
  61. break;
  62. case 'double':
  63. _array_type = Float64Array;
  64. _chunkSize = 8;
  65. break;
  66. }
  67. // increase the data pointer in-place
  68. var _bytes = new _array_type( _data.slice( _dataPointer,
  69. _dataPointer += chunks * _chunkSize ) );
  70. // if required, flip the endianness of the bytes
  71. if ( _nativeLittleEndian != _littleEndian ) {
  72. // we need to flip here since the format doesn't match the native endianness
  73. _bytes = flipEndianness( _bytes, _chunkSize );
  74. }
  75. if ( chunks == 1 ) {
  76. // if only one chunk was requested, just return one value
  77. return _bytes[ 0 ];
  78. }
  79. // return the byte array
  80. return _bytes;
  81. }
  82. //Flips typed array endianness in-place. Based on https://github.com/kig/DataStream.js/blob/master/DataStream.js.
  83. function flipEndianness( array, chunkSize ) {
  84. var u8 = new Uint8Array( array.buffer, array.byteOffset, array.byteLength );
  85. for ( var i = 0; i < array.byteLength; i += chunkSize ) {
  86. for ( var j = i + chunkSize - 1, k = i; j > k; j --, k ++ ) {
  87. var tmp = u8[ k ];
  88. u8[ k ] = u8[ j ];
  89. u8[ j ] = tmp;
  90. }
  91. }
  92. return array;
  93. }
  94. //parse the header
  95. function parseHeader( header ) {
  96. var data, field, fn, i, l, lines, m, _i, _len;
  97. lines = header.split( /\r?\n/ );
  98. for ( _i = 0, _len = lines.length; _i < _len; _i ++ ) {
  99. l = lines[ _i ];
  100. if ( l.match( /NRRD\d+/ ) ) {
  101. headerObject.isNrrd = true;
  102. } else if ( l.match( /^#/ ) ) {
  103. } else if ( m = l.match( /(.*):(.*)/ ) ) {
  104. field = m[ 1 ].trim();
  105. data = m[ 2 ].trim();
  106. fn = THREE.NRRDLoader.prototype.fieldFunctions[ field ];
  107. if ( fn ) {
  108. fn.call( headerObject, data );
  109. } else {
  110. headerObject[ field ] = data;
  111. }
  112. }
  113. }
  114. if ( ! headerObject.isNrrd ) {
  115. throw new Error( 'Not an NRRD file' );
  116. }
  117. if ( headerObject.encoding === 'bz2' || headerObject.encoding === 'bzip2' ) {
  118. throw new Error( 'Bzip is not supported' );
  119. }
  120. if ( ! headerObject.vectors ) {
  121. //if no space direction is set, let's use the identity
  122. headerObject.vectors = [ new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ) ];
  123. //apply spacing if defined
  124. if ( headerObject.spacings ) {
  125. for ( i = 0; i <= 2; i ++ ) {
  126. if ( ! isNaN( headerObject.spacings[ i ] ) ) {
  127. headerObject.vectors[ i ].multiplyScalar( headerObject.spacings[ i ] );
  128. }
  129. }
  130. }
  131. }
  132. }
  133. //parse the data when registred as one of this type : 'text', 'ascii', 'txt'
  134. function parseDataAsText( data, start, end ) {
  135. var number = '';
  136. start = start || 0;
  137. end = end || data.length;
  138. var lastSpace = start;
  139. var value;
  140. //length of the result is the product of the sizes
  141. var lengthOfTheResult = headerObject.sizes.reduce( function( previous, current ) {
  142. return previous * current;
  143. }, 1 );
  144. var base = 10;
  145. if ( headerObject.encoding === 'hex' ) {
  146. base = 16;
  147. }
  148. var result = new headerObject.__array( lengthOfTheResult );
  149. var resultIndex = 0;
  150. var parsingFunction = parseInt;
  151. if ( headerObject.__array === Float32Array || headerObject.__array === Float64Array ) {
  152. parsingFunction = parseFloat;
  153. }
  154. for ( var i = start; i < end; i ++ ) {
  155. value = data[ i ];
  156. //if value is not a space
  157. if ( ( value < 9 || value > 13 ) && value !== 32 ) {
  158. number += String.fromCharCode( value );
  159. }
  160. else {
  161. if ( number !== '' ) {
  162. result[ resultIndex ] = parsingFunction( number, base );
  163. resultIndex ++;
  164. }
  165. number = '';
  166. }
  167. }
  168. if ( number !== '' ) {
  169. result[ resultIndex ] = parsingFunction( number, base );
  170. resultIndex ++;
  171. }
  172. return result;
  173. }
  174. var _bytes = scan( 'uchar', data.byteLength );
  175. var _length = _bytes.length;
  176. var _header = null;
  177. var _data_start = 0;
  178. var i;
  179. for ( i = 1; i < _length; i ++ ) {
  180. if ( _bytes[ i - 1 ] == 10 && _bytes[ i ] == 10 ) {
  181. // we found two line breaks in a row
  182. // now we know what the header is
  183. _header = this.parseChars( _bytes, 0, i - 2 );
  184. // this is were the data starts
  185. _data_start = i + 1;
  186. break;
  187. }
  188. }
  189. // parse the header
  190. parseHeader( _header );
  191. var _data = _bytes.subarray( _data_start ); // the data without header
  192. if ( headerObject.encoding === 'gzip' || headerObject.encoding === 'gz' ) {
  193. // we need to decompress the datastream
  194. // here we start the unzipping and get a typed Uint8Array back
  195. var inflate = new Zlib.Gunzip( new Uint8Array( _data ) );
  196. _data = inflate.decompress();
  197. }
  198. else if ( headerObject.encoding === 'ascii' || headerObject.encoding === 'text' || headerObject.encoding === 'txt' || headerObject.encoding === 'hex' ) {
  199. _data = parseDataAsText( _data );
  200. }
  201. // .. let's use the underlying array buffer
  202. _data = _data.buffer;
  203. var volume = new THREE.Volume();
  204. volume.header = headerObject;
  205. //
  206. // parse the (unzipped) data to a datastream of the correct type
  207. //
  208. volume.data = new headerObject.__array( _data );
  209. // get the min and max intensities
  210. var min_max = volume.computeMinMax();
  211. var min = min_max[ 0 ];
  212. var max = min_max[ 1 ];
  213. // attach the scalar range to the volume
  214. volume.windowLow = min;
  215. volume.windowHigh = max;
  216. // get the image dimensions
  217. volume.dimensions = [ headerObject.sizes[ 0 ], headerObject.sizes[ 1 ], headerObject.sizes[ 2 ] ];
  218. volume.xLength = volume.dimensions[ 0 ];
  219. volume.yLength = volume.dimensions[ 1 ];
  220. volume.zLength = volume.dimensions[ 2 ];
  221. // spacing
  222. var spacingX = ( new THREE.Vector3( headerObject.vectors[ 0 ][ 0 ], headerObject.vectors[ 0 ][ 1 ],
  223. headerObject.vectors[ 0 ][ 2 ] ) ).length();
  224. var spacingY = ( new THREE.Vector3( headerObject.vectors[ 1 ][ 0 ], headerObject.vectors[ 1 ][ 1 ],
  225. headerObject.vectors[ 1 ][ 2 ] ) ).length();
  226. var spacingZ = ( new THREE.Vector3( headerObject.vectors[ 2 ][ 0 ], headerObject.vectors[ 2 ][ 1 ],
  227. headerObject.vectors[ 2 ][ 2 ] ) ).length();
  228. volume.spacing = [ spacingX, spacingY, spacingZ ];
  229. // Create IJKtoRAS matrix
  230. volume.matrix = new THREE.Matrix4();
  231. var _spaceX = 1;
  232. var _spaceY = 1;
  233. var _spaceZ = 1;
  234. if ( headerObject.space == "left-posterior-superior" ) {
  235. _spaceX = - 1;
  236. _spaceY = - 1;
  237. }
  238. else if ( headerObject.space === 'left-anterior-superior' ) {
  239. _spaceX = - 1
  240. }
  241. if ( ! headerObject.vectors ) {
  242. volume.matrix.set( _spaceX, 0, 0, 0,
  243. 0, _spaceY, 0, 0,
  244. 0, 0, _spaceZ, 0,
  245. 0, 0, 0, 1 );
  246. }
  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. _results = [];
  395. for ( _i = 0, _len = parts.length; _i < _len; _i ++ ) {
  396. f = parts[ _i ];
  397. _results.push( parseFloat( f ) );
  398. }
  399. return _results;
  400. } )();
  401. }
  402. }
  403. };
  404. THREE.EventDispatcher.prototype.apply( THREE.NRRDLoader.prototype );