VTKLoader.js 27 KB

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