VTKLoader.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. ( function () {
  2. var VTKLoader = function ( manager ) {
  3. THREE.Loader.call( this, manager );
  4. };
  5. VTKLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  6. constructor: VTKLoader,
  7. load: function ( url, onLoad, onProgress, onError ) {
  8. var scope = this;
  9. var loader = new THREE.FileLoader( scope.manager );
  10. loader.setPath( scope.path );
  11. loader.setResponseType( 'arraybuffer' );
  12. loader.setRequestHeader( scope.requestHeader );
  13. loader.setWithCredentials( scope.withCredentials );
  14. loader.load( url, function ( text ) {
  15. try {
  16. onLoad( scope.parse( text ) );
  17. } catch ( e ) {
  18. if ( onError ) {
  19. onError( e );
  20. } else {
  21. console.error( e );
  22. }
  23. scope.manager.itemError( url );
  24. }
  25. }, onProgress, onError );
  26. },
  27. parse: function ( data ) {
  28. function parseASCII( data ) {
  29. // connectivity of the triangles
  30. var indices = []; // triangles vertices
  31. var positions = []; // red, green, blue colors in the range 0 to 1
  32. var colors = []; // normal vector, one per vertex
  33. var normals = [];
  34. var result; // pattern for detecting the end of a number sequence
  35. var patWord = /^[^\d.\s-]+/; // pattern for reading vertices, 3 floats or integers
  36. var pat3Floats = /(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)\s+(\-?\d+\.?[\d\-\+e]*)/g; // pattern for connectivity, an integer followed by any number of ints
  37. // the first integer is the number of polygon nodes
  38. var patConnectivity = /^(\d+)\s+([\s\d]*)/; // indicates start of vertex data section
  39. var patPOINTS = /^POINTS /; // indicates start of polygon connectivity section
  40. var patPOLYGONS = /^POLYGONS /; // indicates start of triangle strips section
  41. var patTRIANGLE_STRIPS = /^TRIANGLE_STRIPS /; // POINT_DATA number_of_values
  42. var patPOINT_DATA = /^POINT_DATA[ ]+(\d+)/; // CELL_DATA number_of_polys
  43. var patCELL_DATA = /^CELL_DATA[ ]+(\d+)/; // Start of color section
  44. var patCOLOR_SCALARS = /^COLOR_SCALARS[ ]+(\w+)[ ]+3/; // NORMALS Normals float
  45. var patNORMALS = /^NORMALS[ ]+(\w+)[ ]+(\w+)/;
  46. var inPointsSection = false;
  47. var inPolygonsSection = false;
  48. var inTriangleStripSection = false;
  49. var inPointDataSection = false;
  50. var inCellDataSection = false;
  51. var inColorSection = false;
  52. var inNormalsSection = false;
  53. var lines = data.split( '\n' );
  54. for ( var i in lines ) {
  55. var line = lines[ i ].trim();
  56. if ( line.indexOf( 'DATASET' ) === 0 ) {
  57. var dataset = line.split( ' ' )[ 1 ];
  58. if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
  59. } else if ( inPointsSection ) {
  60. // get the vertices
  61. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  62. if ( patWord.exec( line ) !== null ) break;
  63. var x = parseFloat( result[ 1 ] );
  64. var y = parseFloat( result[ 2 ] );
  65. var z = parseFloat( result[ 3 ] );
  66. positions.push( x, y, z );
  67. }
  68. } else if ( inPolygonsSection ) {
  69. if ( ( result = patConnectivity.exec( line ) ) !== null ) {
  70. // numVertices i0 i1 i2 ...
  71. var numVertices = parseInt( result[ 1 ] );
  72. var inds = result[ 2 ].split( /\s+/ );
  73. if ( numVertices >= 3 ) {
  74. var i0 = parseInt( inds[ 0 ] );
  75. var i1, i2;
  76. var k = 1; // split the polygon in numVertices - 2 triangles
  77. for ( var j = 0; j < numVertices - 2; ++ j ) {
  78. i1 = parseInt( inds[ k ] );
  79. i2 = parseInt( inds[ k + 1 ] );
  80. indices.push( i0, i1, i2 );
  81. k ++;
  82. }
  83. }
  84. }
  85. } else if ( inTriangleStripSection ) {
  86. if ( ( result = patConnectivity.exec( line ) ) !== null ) {
  87. // numVertices i0 i1 i2 ...
  88. var numVertices = parseInt( result[ 1 ] );
  89. var inds = result[ 2 ].split( /\s+/ );
  90. if ( numVertices >= 3 ) {
  91. var i0, i1, i2; // split the polygon in numVertices - 2 triangles
  92. for ( var j = 0; j < numVertices - 2; j ++ ) {
  93. if ( j % 2 === 1 ) {
  94. i0 = parseInt( inds[ j ] );
  95. i1 = parseInt( inds[ j + 2 ] );
  96. i2 = parseInt( inds[ j + 1 ] );
  97. indices.push( i0, i1, i2 );
  98. } else {
  99. i0 = parseInt( inds[ j ] );
  100. i1 = parseInt( inds[ j + 1 ] );
  101. i2 = parseInt( inds[ j + 2 ] );
  102. indices.push( i0, i1, i2 );
  103. }
  104. }
  105. }
  106. }
  107. } else if ( inPointDataSection || inCellDataSection ) {
  108. if ( inColorSection ) {
  109. // Get the colors
  110. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  111. if ( patWord.exec( line ) !== null ) break;
  112. var r = parseFloat( result[ 1 ] );
  113. var g = parseFloat( result[ 2 ] );
  114. var b = parseFloat( result[ 3 ] );
  115. colors.push( r, g, b );
  116. }
  117. } else if ( inNormalsSection ) {
  118. // Get the normal vectors
  119. while ( ( result = pat3Floats.exec( line ) ) !== null ) {
  120. if ( patWord.exec( line ) !== null ) break;
  121. var nx = parseFloat( result[ 1 ] );
  122. var ny = parseFloat( result[ 2 ] );
  123. var nz = parseFloat( result[ 3 ] );
  124. normals.push( nx, ny, nz );
  125. }
  126. }
  127. }
  128. if ( patPOLYGONS.exec( line ) !== null ) {
  129. inPolygonsSection = true;
  130. inPointsSection = false;
  131. inTriangleStripSection = false;
  132. } else if ( patPOINTS.exec( line ) !== null ) {
  133. inPolygonsSection = false;
  134. inPointsSection = true;
  135. inTriangleStripSection = false;
  136. } else if ( patTRIANGLE_STRIPS.exec( line ) !== null ) {
  137. inPolygonsSection = false;
  138. inPointsSection = false;
  139. inTriangleStripSection = true;
  140. } else if ( patPOINT_DATA.exec( line ) !== null ) {
  141. inPointDataSection = true;
  142. inPointsSection = false;
  143. inPolygonsSection = false;
  144. inTriangleStripSection = false;
  145. } else if ( patCELL_DATA.exec( line ) !== null ) {
  146. inCellDataSection = true;
  147. inPointsSection = false;
  148. inPolygonsSection = false;
  149. inTriangleStripSection = false;
  150. } else if ( patCOLOR_SCALARS.exec( line ) !== null ) {
  151. inColorSection = true;
  152. inNormalsSection = false;
  153. inPointsSection = false;
  154. inPolygonsSection = false;
  155. inTriangleStripSection = false;
  156. } else if ( patNORMALS.exec( line ) !== null ) {
  157. inNormalsSection = true;
  158. inColorSection = false;
  159. inPointsSection = false;
  160. inPolygonsSection = false;
  161. inTriangleStripSection = false;
  162. }
  163. }
  164. var geometry = new THREE.BufferGeometry();
  165. geometry.setIndex( indices );
  166. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  167. if ( normals.length === positions.length ) {
  168. geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  169. }
  170. if ( colors.length !== indices.length ) {
  171. // stagger
  172. if ( colors.length === positions.length ) {
  173. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( colors, 3 ) );
  174. }
  175. } else {
  176. // cell
  177. geometry = geometry.toNonIndexed();
  178. var numTriangles = geometry.attributes.position.count / 3;
  179. if ( colors.length === numTriangles * 3 ) {
  180. var newColors = [];
  181. for ( var i = 0; i < numTriangles; i ++ ) {
  182. var r = colors[ 3 * i + 0 ];
  183. var g = colors[ 3 * i + 1 ];
  184. var b = colors[ 3 * i + 2 ];
  185. newColors.push( r, g, b );
  186. newColors.push( r, g, b );
  187. newColors.push( r, g, b );
  188. }
  189. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( newColors, 3 ) );
  190. }
  191. }
  192. return geometry;
  193. }
  194. function parseBinary( data ) {
  195. var count, pointIndex, i, numberOfPoints, s;
  196. var buffer = new Uint8Array( data );
  197. var dataView = new DataView( data ); // Points and normals, by default, are empty
  198. var points = [];
  199. var normals = [];
  200. var indices = []; // Going to make a big array of strings
  201. var vtk = [];
  202. var index = 0;
  203. function findString( buffer, start ) {
  204. var index = start;
  205. var c = buffer[ index ];
  206. var s = [];
  207. while ( c !== 10 ) {
  208. s.push( String.fromCharCode( c ) );
  209. index ++;
  210. c = buffer[ index ];
  211. }
  212. return {
  213. start: start,
  214. end: index,
  215. next: index + 1,
  216. parsedString: s.join( '' )
  217. };
  218. }
  219. var state, line;
  220. while ( true ) {
  221. // Get a string
  222. state = findString( buffer, index );
  223. line = state.parsedString;
  224. if ( line.indexOf( 'DATASET' ) === 0 ) {
  225. var dataset = line.split( ' ' )[ 1 ];
  226. if ( dataset !== 'POLYDATA' ) throw new Error( 'Unsupported DATASET type: ' + dataset );
  227. } else if ( line.indexOf( 'POINTS' ) === 0 ) {
  228. vtk.push( line ); // Add the points
  229. numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 ); // Each point is 3 4-byte floats
  230. count = numberOfPoints * 4 * 3;
  231. points = new Float32Array( numberOfPoints * 3 );
  232. pointIndex = state.next;
  233. for ( i = 0; i < numberOfPoints; i ++ ) {
  234. points[ 3 * i ] = dataView.getFloat32( pointIndex, false );
  235. points[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
  236. points[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
  237. pointIndex = pointIndex + 12;
  238. } // increment our next pointer
  239. state.next = state.next + count + 1;
  240. } else if ( line.indexOf( 'TRIANGLE_STRIPS' ) === 0 ) {
  241. var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
  242. var size = parseInt( line.split( ' ' )[ 2 ], 10 ); // 4 byte integers
  243. count = size * 4;
  244. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  245. var indicesIndex = 0;
  246. pointIndex = state.next;
  247. for ( i = 0; i < numberOfStrips; i ++ ) {
  248. // For each strip, read the first value, then record that many more points
  249. var indexCount = dataView.getInt32( pointIndex, false );
  250. var strip = [];
  251. pointIndex += 4;
  252. for ( s = 0; s < indexCount; s ++ ) {
  253. strip.push( dataView.getInt32( pointIndex, false ) );
  254. pointIndex += 4;
  255. } // retrieves the n-2 triangles from the triangle strip
  256. for ( var j = 0; j < indexCount - 2; j ++ ) {
  257. if ( j % 2 ) {
  258. indices[ indicesIndex ++ ] = strip[ j ];
  259. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  260. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  261. } else {
  262. indices[ indicesIndex ++ ] = strip[ j ];
  263. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  264. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  265. }
  266. }
  267. } // increment our next pointer
  268. state.next = state.next + count + 1;
  269. } else if ( line.indexOf( 'POLYGONS' ) === 0 ) {
  270. var numberOfStrips = parseInt( line.split( ' ' )[ 1 ], 10 );
  271. var size = parseInt( line.split( ' ' )[ 2 ], 10 ); // 4 byte integers
  272. count = size * 4;
  273. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  274. var indicesIndex = 0;
  275. pointIndex = state.next;
  276. for ( i = 0; i < numberOfStrips; i ++ ) {
  277. // For each strip, read the first value, then record that many more points
  278. var indexCount = dataView.getInt32( pointIndex, false );
  279. var strip = [];
  280. pointIndex += 4;
  281. for ( s = 0; s < indexCount; s ++ ) {
  282. strip.push( dataView.getInt32( pointIndex, false ) );
  283. pointIndex += 4;
  284. } // divide the polygon in n-2 triangle
  285. for ( var j = 1; j < indexCount - 1; j ++ ) {
  286. indices[ indicesIndex ++ ] = strip[ 0 ];
  287. indices[ indicesIndex ++ ] = strip[ j ];
  288. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  289. }
  290. } // increment our next pointer
  291. state.next = state.next + count + 1;
  292. } else if ( line.indexOf( 'POINT_DATA' ) === 0 ) {
  293. numberOfPoints = parseInt( line.split( ' ' )[ 1 ], 10 ); // Grab the next line
  294. state = findString( buffer, state.next ); // Now grab the binary data
  295. count = numberOfPoints * 4 * 3;
  296. normals = new Float32Array( numberOfPoints * 3 );
  297. pointIndex = state.next;
  298. for ( i = 0; i < numberOfPoints; i ++ ) {
  299. normals[ 3 * i ] = dataView.getFloat32( pointIndex, false );
  300. normals[ 3 * i + 1 ] = dataView.getFloat32( pointIndex + 4, false );
  301. normals[ 3 * i + 2 ] = dataView.getFloat32( pointIndex + 8, false );
  302. pointIndex += 12;
  303. } // Increment past our data
  304. state.next = state.next + count;
  305. } // Increment index
  306. index = state.next;
  307. if ( index >= buffer.byteLength ) {
  308. break;
  309. }
  310. }
  311. var geometry = new THREE.BufferGeometry();
  312. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  313. geometry.setAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  314. if ( normals.length === points.length ) {
  315. geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  316. }
  317. return geometry;
  318. }
  319. function Float32Concat( first, second ) {
  320. var firstLength = first.length,
  321. result = new Float32Array( firstLength + second.length );
  322. result.set( first );
  323. result.set( second, firstLength );
  324. return result;
  325. }
  326. function Int32Concat( first, second ) {
  327. var firstLength = first.length,
  328. result = new Int32Array( firstLength + second.length );
  329. result.set( first );
  330. result.set( second, firstLength );
  331. return result;
  332. }
  333. function parseXML( stringFile ) {
  334. // Changes XML to JSON, based on https://davidwalsh.name/convert-xml-json
  335. function xmlToJson( xml ) {
  336. // Create the return object
  337. var obj = {};
  338. if ( xml.nodeType === 1 ) {
  339. // element
  340. // do attributes
  341. if ( xml.attributes ) {
  342. if ( xml.attributes.length > 0 ) {
  343. obj[ 'attributes' ] = {};
  344. for ( var j = 0; j < xml.attributes.length; j ++ ) {
  345. var attribute = xml.attributes.item( j );
  346. obj[ 'attributes' ][ attribute.nodeName ] = attribute.nodeValue.trim();
  347. }
  348. }
  349. }
  350. } else if ( xml.nodeType === 3 ) {
  351. // text
  352. obj = xml.nodeValue.trim();
  353. } // do children
  354. if ( xml.hasChildNodes() ) {
  355. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  356. var item = xml.childNodes.item( i );
  357. var nodeName = item.nodeName;
  358. if ( typeof obj[ nodeName ] === 'undefined' ) {
  359. var tmp = xmlToJson( item );
  360. if ( tmp !== '' ) obj[ nodeName ] = tmp;
  361. } else {
  362. if ( typeof obj[ nodeName ].push === 'undefined' ) {
  363. var old = obj[ nodeName ];
  364. obj[ nodeName ] = [ old ];
  365. }
  366. var tmp = xmlToJson( item );
  367. if ( tmp !== '' ) obj[ nodeName ].push( tmp );
  368. }
  369. }
  370. }
  371. return obj;
  372. } // Taken from Base64-js
  373. function Base64toByteArray( b64 ) {
  374. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  375. var i;
  376. var lookup = [];
  377. var revLookup = [];
  378. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  379. var len = code.length;
  380. for ( i = 0; i < len; i ++ ) {
  381. lookup[ i ] = code[ i ];
  382. }
  383. for ( i = 0; i < len; ++ i ) {
  384. revLookup[ code.charCodeAt( i ) ] = i;
  385. }
  386. revLookup[ '-'.charCodeAt( 0 ) ] = 62;
  387. revLookup[ '_'.charCodeAt( 0 ) ] = 63;
  388. var j, l, tmp, placeHolders, arr;
  389. var len = b64.length;
  390. if ( len % 4 > 0 ) {
  391. throw new Error( 'Invalid string. Length must be a multiple of 4' );
  392. }
  393. placeHolders = b64[ len - 2 ] === '=' ? 2 : b64[ len - 1 ] === '=' ? 1 : 0;
  394. arr = new Arr( len * 3 / 4 - placeHolders );
  395. l = placeHolders > 0 ? len - 4 : len;
  396. var L = 0;
  397. for ( i = 0, j = 0; i < l; i += 4, j += 3 ) {
  398. tmp = revLookup[ b64.charCodeAt( i ) ] << 18 | revLookup[ b64.charCodeAt( i + 1 ) ] << 12 | revLookup[ b64.charCodeAt( i + 2 ) ] << 6 | revLookup[ b64.charCodeAt( i + 3 ) ];
  399. arr[ L ++ ] = ( tmp & 0xFF0000 ) >> 16;
  400. arr[ L ++ ] = ( tmp & 0xFF00 ) >> 8;
  401. arr[ L ++ ] = tmp & 0xFF;
  402. }
  403. if ( placeHolders === 2 ) {
  404. tmp = revLookup[ b64.charCodeAt( i ) ] << 2 | revLookup[ b64.charCodeAt( i + 1 ) ] >> 4;
  405. arr[ L ++ ] = tmp & 0xFF;
  406. } else if ( placeHolders === 1 ) {
  407. tmp = revLookup[ b64.charCodeAt( i ) ] << 10 | revLookup[ b64.charCodeAt( i + 1 ) ] << 4 | revLookup[ b64.charCodeAt( i + 2 ) ] >> 2;
  408. arr[ L ++ ] = tmp >> 8 & 0xFF;
  409. arr[ L ++ ] = tmp & 0xFF;
  410. }
  411. return arr;
  412. }
  413. function parseDataArray( ele, compressed ) {
  414. var numBytes = 0;
  415. if ( json.attributes.header_type === 'UInt64' ) {
  416. numBytes = 8;
  417. } else if ( json.attributes.header_type === 'UInt32' ) {
  418. numBytes = 4;
  419. } // Check the format
  420. if ( ele.attributes.format === 'binary' && compressed ) {
  421. var rawData, content, byteData, blocks, cSizeStart, headerSize, padding, dataOffsets, currentOffset;
  422. if ( ele.attributes.type === 'Float32' ) {
  423. var txt = new Float32Array();
  424. } else if ( ele.attributes.type === 'Int64' ) {
  425. var txt = new Int32Array();
  426. } // VTP data with the header has the following structure:
  427. // [#blocks][#u-size][#p-size][#c-size-1][#c-size-2]...[#c-size-#blocks][DATA]
  428. //
  429. // Each token is an integer value whose type is specified by "header_type" at the top of the file (UInt32 if no type specified). The token meanings are:
  430. // [#blocks] = Number of blocks
  431. // [#u-size] = Block size before compression
  432. // [#p-size] = Size of last partial block (zero if it not needed)
  433. // [#c-size-i] = Size in bytes of block i after compression
  434. //
  435. // The [DATA] portion stores contiguously every block appended together. The offset from the beginning of the data section to the beginning of a block is
  436. // computed by summing the compressed block sizes from preceding blocks according to the header.
  437. rawData = ele[ '#text' ];
  438. byteData = Base64toByteArray( rawData );
  439. blocks = byteData[ 0 ];
  440. for ( var i = 1; i < numBytes - 1; i ++ ) {
  441. blocks = blocks | byteData[ i ] << i * numBytes;
  442. }
  443. headerSize = ( blocks + 3 ) * numBytes;
  444. padding = headerSize % 3 > 0 ? 3 - headerSize % 3 : 0;
  445. headerSize = headerSize + padding;
  446. dataOffsets = [];
  447. currentOffset = headerSize;
  448. dataOffsets.push( currentOffset ); // Get the blocks sizes after the compression.
  449. // There are three blocks before c-size-i, so we skip 3*numBytes
  450. cSizeStart = 3 * numBytes;
  451. for ( var i = 0; i < blocks; i ++ ) {
  452. var currentBlockSize = byteData[ i * numBytes + cSizeStart ];
  453. for ( var j = 1; j < numBytes - 1; j ++ ) {
  454. // Each data point consists of 8 bytes regardless of the header type
  455. currentBlockSize = currentBlockSize | byteData[ i * numBytes + cSizeStart + j ] << j * 8;
  456. }
  457. currentOffset = currentOffset + currentBlockSize;
  458. dataOffsets.push( currentOffset );
  459. }
  460. for ( var i = 0; i < dataOffsets.length - 1; i ++ ) {
  461. var data = fflate.unzlibSync( byteData.slice( dataOffsets[ i ], dataOffsets[ i + 1 ] ) ); // eslint-disable-line no-undef
  462. content = data.buffer;
  463. if ( ele.attributes.type === 'Float32' ) {
  464. content = new Float32Array( content );
  465. txt = Float32Concat( txt, content );
  466. } else if ( ele.attributes.type === 'Int64' ) {
  467. content = new Int32Array( content );
  468. txt = Int32Concat( txt, content );
  469. }
  470. }
  471. delete ele[ '#text' ];
  472. if ( ele.attributes.type === 'Int64' ) {
  473. if ( ele.attributes.format === 'binary' ) {
  474. txt = txt.filter( function ( el, idx ) {
  475. if ( idx % 2 !== 1 ) return true;
  476. } );
  477. }
  478. }
  479. } else {
  480. if ( ele.attributes.format === 'binary' && ! compressed ) {
  481. var content = Base64toByteArray( ele[ '#text' ] ); // VTP data for the uncompressed case has the following structure:
  482. // [#bytes][DATA]
  483. // where "[#bytes]" is an integer value specifying the number of bytes in the block of data following it.
  484. content = content.slice( numBytes ).buffer;
  485. } else {
  486. if ( ele[ '#text' ] ) {
  487. var content = ele[ '#text' ].split( /\s+/ ).filter( function ( el ) {
  488. if ( el !== '' ) return el;
  489. } );
  490. } else {
  491. var content = new Int32Array( 0 ).buffer;
  492. }
  493. }
  494. delete ele[ '#text' ]; // Get the content and optimize it
  495. if ( ele.attributes.type === 'Float32' ) {
  496. var txt = new Float32Array( content );
  497. } else if ( ele.attributes.type === 'Int32' ) {
  498. var txt = new Int32Array( content );
  499. } else if ( ele.attributes.type === 'Int64' ) {
  500. var txt = new Int32Array( content );
  501. if ( ele.attributes.format === 'binary' ) {
  502. txt = txt.filter( function ( el, idx ) {
  503. if ( idx % 2 !== 1 ) return true;
  504. } );
  505. }
  506. }
  507. } // endif ( ele.attributes.format === 'binary' && compressed )
  508. return txt;
  509. } // Main part
  510. // Get Dom
  511. var dom = null;
  512. if ( window.DOMParser ) {
  513. try {
  514. dom = new DOMParser().parseFromString( stringFile, 'text/xml' );
  515. } catch ( e ) {
  516. dom = null;
  517. }
  518. } else if ( window.ActiveXObject ) {
  519. try {
  520. dom = new ActiveXObject( 'Microsoft.XMLDOM' ); // eslint-disable-line no-undef
  521. dom.async = false;
  522. if ( ! dom.loadXML() ) {
  523. throw new Error( dom.parseError.reason + dom.parseError.srcText );
  524. }
  525. } catch ( e ) {
  526. dom = null;
  527. }
  528. } else {
  529. throw new Error( 'Cannot parse xml string!' );
  530. } // Get the doc
  531. var doc = dom.documentElement; // Convert to json
  532. var json = xmlToJson( doc );
  533. var points = [];
  534. var normals = [];
  535. var indices = [];
  536. if ( json.PolyData ) {
  537. var piece = json.PolyData.Piece;
  538. var compressed = json.attributes.hasOwnProperty( 'compressor' ); // Can be optimized
  539. // Loop through the sections
  540. var sections = [ 'PointData', 'Points', 'Strips', 'Polys' ]; // +['CellData', 'Verts', 'Lines'];
  541. var sectionIndex = 0,
  542. numberOfSections = sections.length;
  543. while ( sectionIndex < numberOfSections ) {
  544. var section = piece[ sections[ sectionIndex ] ]; // If it has a DataArray in it
  545. if ( section && section.DataArray ) {
  546. // Depending on the number of DataArrays
  547. if ( Object.prototype.toString.call( section.DataArray ) === '[object Array]' ) {
  548. var arr = section.DataArray;
  549. } else {
  550. var arr = [ section.DataArray ];
  551. }
  552. var dataArrayIndex = 0,
  553. numberOfDataArrays = arr.length;
  554. while ( dataArrayIndex < numberOfDataArrays ) {
  555. // Parse the DataArray
  556. if ( '#text' in arr[ dataArrayIndex ] && arr[ dataArrayIndex ][ '#text' ].length > 0 ) {
  557. arr[ dataArrayIndex ].text = parseDataArray( arr[ dataArrayIndex ], compressed );
  558. }
  559. dataArrayIndex ++;
  560. }
  561. switch ( sections[ sectionIndex ] ) {
  562. // if iti is point data
  563. case 'PointData':
  564. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  565. var normalsName = section.attributes.Normals;
  566. if ( numberOfPoints > 0 ) {
  567. for ( var i = 0, len = arr.length; i < len; i ++ ) {
  568. if ( normalsName === arr[ i ].attributes.Name ) {
  569. var components = arr[ i ].attributes.NumberOfComponents;
  570. normals = new Float32Array( numberOfPoints * components );
  571. normals.set( arr[ i ].text, 0 );
  572. }
  573. }
  574. }
  575. break;
  576. // if it is points
  577. case 'Points':
  578. var numberOfPoints = parseInt( piece.attributes.NumberOfPoints );
  579. if ( numberOfPoints > 0 ) {
  580. var components = section.DataArray.attributes.NumberOfComponents;
  581. points = new Float32Array( numberOfPoints * components );
  582. points.set( section.DataArray.text, 0 );
  583. }
  584. break;
  585. // if it is strips
  586. case 'Strips':
  587. var numberOfStrips = parseInt( piece.attributes.NumberOfStrips );
  588. if ( numberOfStrips > 0 ) {
  589. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  590. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  591. connectivity.set( section.DataArray[ 0 ].text, 0 );
  592. offset.set( section.DataArray[ 1 ].text, 0 );
  593. var size = numberOfStrips + connectivity.length;
  594. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  595. var indicesIndex = 0;
  596. for ( var i = 0, len = numberOfStrips; i < len; i ++ ) {
  597. var strip = [];
  598. for ( var s = 0, len1 = offset[ i ], len0 = 0; s < len1 - len0; s ++ ) {
  599. strip.push( connectivity[ s ] );
  600. if ( i > 0 ) len0 = offset[ i - 1 ];
  601. }
  602. for ( var j = 0, len1 = offset[ i ], len0 = 0; j < len1 - len0 - 2; j ++ ) {
  603. if ( j % 2 ) {
  604. indices[ indicesIndex ++ ] = strip[ j ];
  605. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  606. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  607. } else {
  608. indices[ indicesIndex ++ ] = strip[ j ];
  609. indices[ indicesIndex ++ ] = strip[ j + 1 ];
  610. indices[ indicesIndex ++ ] = strip[ j + 2 ];
  611. }
  612. if ( i > 0 ) len0 = offset[ i - 1 ];
  613. }
  614. }
  615. }
  616. break;
  617. // if it is polys
  618. case 'Polys':
  619. var numberOfPolys = parseInt( piece.attributes.NumberOfPolys );
  620. if ( numberOfPolys > 0 ) {
  621. var connectivity = new Int32Array( section.DataArray[ 0 ].text.length );
  622. var offset = new Int32Array( section.DataArray[ 1 ].text.length );
  623. connectivity.set( section.DataArray[ 0 ].text, 0 );
  624. offset.set( section.DataArray[ 1 ].text, 0 );
  625. var size = numberOfPolys + connectivity.length;
  626. indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
  627. var indicesIndex = 0,
  628. connectivityIndex = 0;
  629. var i = 0,
  630. len = numberOfPolys,
  631. len0 = 0;
  632. while ( i < len ) {
  633. var poly = [];
  634. var s = 0,
  635. len1 = offset[ i ];
  636. while ( s < len1 - len0 ) {
  637. poly.push( connectivity[ connectivityIndex ++ ] );
  638. s ++;
  639. }
  640. var j = 1;
  641. while ( j < len1 - len0 - 1 ) {
  642. indices[ indicesIndex ++ ] = poly[ 0 ];
  643. indices[ indicesIndex ++ ] = poly[ j ];
  644. indices[ indicesIndex ++ ] = poly[ j + 1 ];
  645. j ++;
  646. }
  647. i ++;
  648. len0 = offset[ i - 1 ];
  649. }
  650. }
  651. break;
  652. default:
  653. break;
  654. }
  655. }
  656. sectionIndex ++;
  657. }
  658. var geometry = new THREE.BufferGeometry();
  659. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  660. geometry.setAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  661. if ( normals.length === points.length ) {
  662. geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  663. }
  664. return geometry;
  665. } else {
  666. throw new Error( 'Unsupported DATASET type' );
  667. }
  668. } // get the 5 first lines of the files to check if there is the key word binary
  669. var meta = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 250 ) ).split( '\n' );
  670. if ( meta[ 0 ].indexOf( 'xml' ) !== - 1 ) {
  671. return parseXML( THREE.LoaderUtils.decodeText( data ) );
  672. } else if ( meta[ 2 ].includes( 'ASCII' ) ) {
  673. return parseASCII( THREE.LoaderUtils.decodeText( data ) );
  674. } else {
  675. return parseBinary( data );
  676. }
  677. }
  678. } );
  679. THREE.VTKLoader = VTKLoader;
  680. } )();