VTKLoader.js 27 KB

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