VTKLoader.js 28 KB

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