VTKLoader.js 28 KB

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