VTKLoader.js 27 KB

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