VTKLoader.js 27 KB

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