VTKLoader.js 27 KB

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