VTKLoader.js 24 KB

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