VTKLoader.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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. var xmlToJson = function (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 != ""){
  376. obj[nodeName] = tmp;
  377. }
  378. } else {
  379. if (typeof(obj[nodeName].push) == "undefined") {
  380. var old = obj[nodeName];
  381. obj[nodeName] = [];
  382. obj[nodeName].push(old);
  383. }
  384. var tmp = xmlToJson(item);
  385. if(tmp != ""){
  386. obj[nodeName].push(tmp);
  387. }
  388. }
  389. }
  390. }
  391. return obj;
  392. };
  393. // Taken from Base64-js
  394. var Base64toByteArray = function(b64) {
  395. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  396. var i;
  397. var lookup = [];
  398. var revLookup = [];
  399. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  400. var len = code.length;
  401. for (i = 0; i < len; i++) {
  402. lookup[i] = code[i];
  403. }
  404. for (i = 0; i < len; ++i) {
  405. revLookup[code.charCodeAt(i)] = i;
  406. }
  407. revLookup['-'.charCodeAt(0)] = 62;
  408. revLookup['_'.charCodeAt(0)] = 63;
  409. var j, l, tmp, placeHolders, arr;
  410. var len = b64.length;
  411. if (len % 4 > 0) {
  412. throw new Error('Invalid string. Length must be a multiple of 4');
  413. }
  414. placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
  415. arr = new Arr(len * 3 / 4 - placeHolders);
  416. l = placeHolders > 0 ? len - 4 : len;
  417. var L = 0;
  418. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  419. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
  420. arr[L++] = (tmp & 0xFF0000) >> 16;
  421. arr[L++] = (tmp & 0xFF00) >> 8;
  422. arr[L++] = tmp & 0xFF;
  423. }
  424. if (placeHolders === 2) {
  425. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
  426. arr[L++] = tmp & 0xFF;
  427. } else if (placeHolders === 1) {
  428. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
  429. arr[L++] = (tmp >> 8) & 0xFF;
  430. arr[L++] = tmp & 0xFF;
  431. }
  432. return arr;
  433. }
  434. var parseDataArray = function(ele, compressed){
  435. // Check the format
  436. if (ele.attributes.format == "binary"){
  437. if(compressed){
  438. // Split the blob_header and compressed Data
  439. if(ele["#text"].indexOf('==') != -1){
  440. var data = ele["#text"].split("==");
  441. //console.log(data);
  442. if (data.length == 2){
  443. var blob = data.shift();
  444. var content = data.shift();
  445. if(content == ""){
  446. content = blob + "==";
  447. }
  448. }else if(data.length > 2){
  449. var blob = data.shift();
  450. var content = data.shift();
  451. content = content + "==";
  452. }else if (data.length < 2){
  453. var content = data.shift();
  454. content = content + "==";
  455. }
  456. // Convert to bytearray
  457. var arr = Base64toByteArray(content);
  458. // decompress
  459. var inflate = new Zlib.Inflate(arr,{resize:true,verify:true});
  460. var content = inflate.decompress();
  461. }else{
  462. var content = Base64toByteArray(ele["#text"]);
  463. }
  464. }else{
  465. var content = Base64toByteArray(ele["#text"]);
  466. }
  467. var content = content.buffer;
  468. }else{
  469. if(ele["#text"]){
  470. var content = ele["#text"].replace(/\n/g," ").split(" ").filter(function(el,idx,arr){
  471. if(el != ""){
  472. return el;
  473. }
  474. });
  475. }else{
  476. var content = new Int32Array(0).buffer;
  477. }
  478. }
  479. delete ele["#text"];
  480. // Get the content and optimize it
  481. if(ele.attributes.type == 'Float32'){
  482. var txt = new Float32Array(content);
  483. if(ele.attributes.format == "binary"){
  484. if(!compressed){
  485. txt = txt.filter(function(el,idx,arr){if(idx != 0){return true;}});
  486. }
  487. }
  488. }else if (ele.attributes.type == 'Int64'){
  489. var txt = new Int32Array(content);
  490. if(ele.attributes.format == "binary"){
  491. if(!compressed){
  492. txt = txt.filter(function(el,idx,arr){if(idx!=0){return true;}});
  493. }
  494. txt = txt.filter(function(el,idx,arr){if(idx%2!=1){return true;}});
  495. }
  496. }
  497. //console.log(txt);
  498. return txt;
  499. }
  500. // Main part
  501. // Get Dom
  502. var dom = null;
  503. if (window.DOMParser) {
  504. try {
  505. dom = (new DOMParser()).parseFromString(stringFile, "text/xml");
  506. }catch (e) {
  507. dom = null;
  508. }
  509. }else if (window.ActiveXObject) {
  510. try {
  511. dom = new ActiveXObject('Microsoft.XMLDOM');
  512. dom.async = false;
  513. if (!dom.loadXML(xml)){
  514. throw new Error(dom.parseError.reason + dom.parseError.srcText);
  515. }
  516. }catch (e) {
  517. dom = null;
  518. }
  519. }else{
  520. throw new Error("Cannot parse xml string!");
  521. }
  522. // Get the doc
  523. var doc = dom.documentElement;
  524. // Convert to json
  525. var json = xmlToJson(doc);
  526. var points = [];
  527. var normals = [];
  528. var indices = [];
  529. if(json.PolyData){
  530. var piece = json.PolyData.Piece;
  531. var compressed = json.attributes.hasOwnProperty("compressor");
  532. // Can be optimized
  533. // Loop through the sections
  534. var sections = ["PointData", "Points", "Strips", "Polys"];// +["CellData", "Verts", "Lines"];
  535. var sectionIndex = 0, numberOfSections = sections.length;
  536. while (sectionIndex < numberOfSections){
  537. var section = piece[sections[sectionIndex]];
  538. // If it has a DataArray in it
  539. if(section.DataArray){
  540. // Depending on the number of DataArrays
  541. if(Object.prototype.toString.call( section.DataArray ) === '[object Array]'){
  542. var arr = section.DataArray;
  543. }else{
  544. var arr = [section.DataArray];
  545. }
  546. var dataArrayIndex = 0, numberOfDataArrays = arr.length;
  547. while(dataArrayIndex < numberOfDataArrays){
  548. // Parse the DataArray
  549. arr[dataArrayIndex].text = parseDataArray(arr[dataArrayIndex],compressed);
  550. dataArrayIndex++;
  551. }
  552. switch(sections[sectionIndex]){
  553. // if iti is point data
  554. case "PointData" :
  555. var numberOfPoints = parseInt(piece.attributes.NumberOfPoints);
  556. var normalsName = section.attributes.Normals;
  557. if (numberOfPoints > 0){
  558. for(var i = 0, len = arr.length; i < len; i++){
  559. if(normalsName == arr[i].attributes.Name){
  560. var components = arr[i].attributes.NumberOfComponents;
  561. normals = new Float32Array(numberOfPoints * components);
  562. normals.set(arr[i].text,0);
  563. }
  564. }
  565. }
  566. //console.log("Normals", normals);
  567. break;
  568. // if it is points
  569. case "Points" :
  570. var numberOfPoints = parseInt(piece.attributes.NumberOfPoints);
  571. if (numberOfPoints > 0){
  572. var components = section.DataArray.attributes.NumberOfComponents;
  573. points = new Float32Array( numberOfPoints * components );
  574. points.set(section.DataArray.text, 0);
  575. }
  576. //console.log("Points", points);
  577. break;
  578. // if it is strips
  579. case "Strips" :
  580. var numberOfStrips = parseInt(piece.attributes.NumberOfStrips);
  581. if(numberOfStrips > 0){
  582. var connectivity = new Int32Array(section.DataArray[0].text.length);
  583. var offset = new Int32Array(section.DataArray[1].text.length);
  584. connectivity.set(section.DataArray[0].text, 0);
  585. offset.set(section.DataArray[1].text, 0);
  586. var size = numberOfStrips + connectivity.length;
  587. indices = new Uint32Array( 3 * size - 9 * numberOfStrips );
  588. var indicesIndex = 0;
  589. for (var i = 0,len = numberOfStrips; i < len; i++) {
  590. var strip = [];
  591. for (var s = 0,len1 = offset[i], len0 = 0; s < len1 - len0; s++) {
  592. strip.push (connectivity[s]);
  593. if(i > 0){
  594. len0 = offset[i-1];
  595. }
  596. }
  597. for (var j = 0,len1 = offset[i], len0 = 0; j < len1 - len0 - 2; j++) {
  598. if ( j % 2 ) {
  599. indices[ indicesIndex++ ] = strip[ j ];
  600. indices[ indicesIndex++ ] = strip[ j + 2 ];
  601. indices[ indicesIndex++ ] = strip[ j + 1 ];
  602. }else{
  603. indices[ indicesIndex++ ] = strip[ j ];
  604. indices[ indicesIndex++ ] = strip[ j + 1 ];
  605. indices[ indicesIndex++ ] = strip[ j + 2 ];
  606. }
  607. if(i > 0){
  608. len0 = offset[i-1];
  609. }
  610. }
  611. }
  612. }
  613. //console.log("Strips", indices);
  614. break;
  615. // if it is polys
  616. case "Polys" :
  617. var numberOfPolys = parseInt(piece.attributes.NumberOfPolys);
  618. if(numberOfPolys > 0){
  619. var connectivity = new Int32Array(section.DataArray[0].text.length);
  620. var offset = new Int32Array(section.DataArray[1].text.length);
  621. connectivity.set(section.DataArray[0].text, 0);
  622. offset.set(section.DataArray[1].text, 0);
  623. var size = numberOfPolys + connectivity.length;
  624. indices = new Uint32Array( 3 * size - 9 * numberOfPolys );
  625. var indicesIndex = 0, connectivityIndex = 0;
  626. var i = 0,len = numberOfPolys, len0 = 0;
  627. while(i < len){
  628. var poly = [];
  629. var s = 0, len1 = offset[i];
  630. while(s < len1 - len0){
  631. poly.push (connectivity[connectivityIndex++]);
  632. s++;
  633. }
  634. var j = 1;
  635. while(j < len1 - len0 - 1){
  636. indices[ indicesIndex++ ] = poly[ 0 ];
  637. indices[ indicesIndex++ ] = poly[ j ];
  638. indices[ indicesIndex++ ] = poly[ j + 1 ];
  639. j++;
  640. }
  641. i++;
  642. len0 = offset[i-1];
  643. }
  644. }
  645. //console.log("Polys", indices);
  646. break;
  647. default :
  648. break;
  649. }
  650. }
  651. sectionIndex++;
  652. }
  653. var geometry = new THREE.BufferGeometry();
  654. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  655. geometry.addAttribute( 'position', new THREE.BufferAttribute( points, 3 ) );
  656. if ( normals.length == points.length ) {
  657. geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  658. }
  659. //console.log(json);
  660. return geometry;
  661. }else{
  662. /* TODO for vtu,vti,and other xml formats*/
  663. }
  664. }
  665. function getStringFile(data){
  666. var stringFile = '';
  667. var charArray = new Uint8Array( data );
  668. var i = 0;
  669. var len = charArray.length;
  670. while(len--){
  671. stringFile += String.fromCharCode( charArray[ i++ ] );
  672. }
  673. return stringFile;
  674. }
  675. // get the 5 first lines of the files to check if there is the key word binary
  676. var meta = String.fromCharCode.apply( null, new Uint8Array( data, 0, 250 ) ).split( '\n' );
  677. if (meta[0].indexOf("xml") != -1){
  678. var stringFile = getStringFile(data);
  679. return parseXML(stringFile);
  680. }else if ( meta[ 2 ].includes( 'ASCII' ) ) {
  681. var stringFile = getStringFile(data);
  682. return parseASCII( stringFile );
  683. } else {
  684. return parseBinary( data );
  685. }
  686. }
  687. };
  688. THREE.EventDispatcher.prototype.apply( THREE.VTKLoader.prototype );