VTKLoader.js 28 KB

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