VTKLoader.js 28 KB

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