VTKLoader.js 30 KB

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