NRRDLoader.js 13 KB

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