VTKLoader.js 27 KB

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