VTKLoader.js 27 KB

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