VTKLoader.js 28 KB

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