VTKLoader.js 27 KB

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