2
0

VTKLoader.js 27 KB

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