1
0

VTKLoader.js 30 KB

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