VTKLoader.js 27 KB

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