PLYLoader.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Loader,
  6. Color,
  7. SRGBColorSpace
  8. } from 'three';
  9. /**
  10. * Description: A THREE loader for PLY ASCII files (known as the Polygon
  11. * File Format or the Stanford Triangle Format).
  12. *
  13. * Limitations: ASCII decoding assumes file is UTF-8.
  14. *
  15. * Usage:
  16. * const loader = new PLYLoader();
  17. * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
  18. *
  19. * scene.add( new THREE.Mesh( geometry ) );
  20. *
  21. * } );
  22. *
  23. * If the PLY file uses non standard property names, they can be mapped while
  24. * loading. For example, the following maps the properties
  25. * “diffuse_(red|green|blue)” in the file to standard color names.
  26. *
  27. * loader.setPropertyNameMapping( {
  28. * diffuse_red: 'red',
  29. * diffuse_green: 'green',
  30. * diffuse_blue: 'blue'
  31. * } );
  32. *
  33. * Custom properties outside of the defaults for position, uv, normal
  34. * and color attributes can be added using the setCustomPropertyNameMapping method.
  35. * For example, the following maps the element properties “custom_property_a”
  36. * and “custom_property_b” to an attribute “customAttribute” with an item size of 2.
  37. * Attribute item sizes are set from the number of element properties in the property array.
  38. *
  39. * loader.setCustomPropertyNameMapping( {
  40. * customAttribute: ['custom_property_a', 'custom_property_b'],
  41. * } );
  42. *
  43. */
  44. const _color = new Color();
  45. class PLYLoader extends Loader {
  46. constructor( manager ) {
  47. super( manager );
  48. this.propertyNameMapping = {};
  49. this.customPropertyMapping = {};
  50. }
  51. load( url, onLoad, onProgress, onError ) {
  52. const scope = this;
  53. const loader = new FileLoader( this.manager );
  54. loader.setPath( this.path );
  55. loader.setResponseType( 'arraybuffer' );
  56. loader.setRequestHeader( this.requestHeader );
  57. loader.setWithCredentials( this.withCredentials );
  58. loader.load( url, function ( text ) {
  59. try {
  60. onLoad( scope.parse( text ) );
  61. } catch ( e ) {
  62. if ( onError ) {
  63. onError( e );
  64. } else {
  65. console.error( e );
  66. }
  67. scope.manager.itemError( url );
  68. }
  69. }, onProgress, onError );
  70. }
  71. setPropertyNameMapping( mapping ) {
  72. this.propertyNameMapping = mapping;
  73. }
  74. setCustomPropertyNameMapping( mapping ) {
  75. this.customPropertyMapping = mapping;
  76. }
  77. parse( data ) {
  78. function parseHeader( data, headerLength = 0 ) {
  79. const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
  80. let headerText = '';
  81. const result = patternHeader.exec( data );
  82. if ( result !== null ) {
  83. headerText = result[ 1 ];
  84. }
  85. const header = {
  86. comments: [],
  87. elements: [],
  88. headerLength: headerLength,
  89. objInfo: ''
  90. };
  91. const lines = headerText.split( /\r\n|\r|\n/ );
  92. let currentElement;
  93. function make_ply_element_property( propertValues, propertyNameMapping ) {
  94. const property = { type: propertValues[ 0 ] };
  95. if ( property.type === 'list' ) {
  96. property.name = propertValues[ 3 ];
  97. property.countType = propertValues[ 1 ];
  98. property.itemType = propertValues[ 2 ];
  99. } else {
  100. property.name = propertValues[ 1 ];
  101. }
  102. if ( property.name in propertyNameMapping ) {
  103. property.name = propertyNameMapping[ property.name ];
  104. }
  105. return property;
  106. }
  107. for ( let i = 0; i < lines.length; i ++ ) {
  108. let line = lines[ i ];
  109. line = line.trim();
  110. if ( line === '' ) continue;
  111. const lineValues = line.split( /\s+/ );
  112. const lineType = lineValues.shift();
  113. line = lineValues.join( ' ' );
  114. switch ( lineType ) {
  115. case 'format':
  116. header.format = lineValues[ 0 ];
  117. header.version = lineValues[ 1 ];
  118. break;
  119. case 'comment':
  120. header.comments.push( line );
  121. break;
  122. case 'element':
  123. if ( currentElement !== undefined ) {
  124. header.elements.push( currentElement );
  125. }
  126. currentElement = {};
  127. currentElement.name = lineValues[ 0 ];
  128. currentElement.count = parseInt( lineValues[ 1 ] );
  129. currentElement.properties = [];
  130. break;
  131. case 'property':
  132. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  133. break;
  134. case 'obj_info':
  135. header.objInfo = line;
  136. break;
  137. default:
  138. console.log( 'unhandled', lineType, lineValues );
  139. }
  140. }
  141. if ( currentElement !== undefined ) {
  142. header.elements.push( currentElement );
  143. }
  144. return header;
  145. }
  146. function parseASCIINumber( n, type ) {
  147. switch ( type ) {
  148. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  149. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  150. return parseInt( n );
  151. case 'float': case 'double': case 'float32': case 'float64':
  152. return parseFloat( n );
  153. }
  154. }
  155. function parseASCIIElement( properties, tokens ) {
  156. const element = {};
  157. for ( let i = 0; i < properties.length; i ++ ) {
  158. if ( tokens.empty() ) return null;
  159. if ( properties[ i ].type === 'list' ) {
  160. const list = [];
  161. const n = parseASCIINumber( tokens.next(), properties[ i ].countType );
  162. for ( let j = 0; j < n; j ++ ) {
  163. if ( tokens.empty() ) return null;
  164. list.push( parseASCIINumber( tokens.next(), properties[ i ].itemType ) );
  165. }
  166. element[ properties[ i ].name ] = list;
  167. } else {
  168. element[ properties[ i ].name ] = parseASCIINumber( tokens.next(), properties[ i ].type );
  169. }
  170. }
  171. return element;
  172. }
  173. function createBuffer() {
  174. const buffer = {
  175. indices: [],
  176. vertices: [],
  177. normals: [],
  178. uvs: [],
  179. faceVertexUvs: [],
  180. colors: [],
  181. faceVertexColors: []
  182. };
  183. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  184. buffer[ customProperty ] = [];
  185. }
  186. return buffer;
  187. }
  188. function mapElementAttributes( properties ) {
  189. const elementNames = properties.map( property => {
  190. return property.name;
  191. } );
  192. function findAttrName( names ) {
  193. for ( let i = 0, l = names.length; i < l; i ++ ) {
  194. const name = names[ i ];
  195. if ( elementNames.includes( name ) ) return name;
  196. }
  197. return null;
  198. }
  199. return {
  200. attrX: findAttrName( [ 'x', 'px', 'posx' ] ) || 'x',
  201. attrY: findAttrName( [ 'y', 'py', 'posy' ] ) || 'y',
  202. attrZ: findAttrName( [ 'z', 'pz', 'posz' ] ) || 'z',
  203. attrNX: findAttrName( [ 'nx', 'normalx' ] ),
  204. attrNY: findAttrName( [ 'ny', 'normaly' ] ),
  205. attrNZ: findAttrName( [ 'nz', 'normalz' ] ),
  206. attrS: findAttrName( [ 's', 'u', 'texture_u', 'tx' ] ),
  207. attrT: findAttrName( [ 't', 'v', 'texture_v', 'ty' ] ),
  208. attrR: findAttrName( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] ),
  209. attrG: findAttrName( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] ),
  210. attrB: findAttrName( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] ),
  211. };
  212. }
  213. function parseASCII( data, header ) {
  214. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  215. const buffer = createBuffer();
  216. const patternBody = /end_header\s+(\S[\s\S]*\S|\S)\s*$/;
  217. let body, matches;
  218. if ( ( matches = patternBody.exec( data ) ) !== null ) {
  219. body = matches[ 1 ].split( /\s+/ );
  220. } else {
  221. body = [ ];
  222. }
  223. const tokens = new ArrayStream( body );
  224. loop: for ( let i = 0; i < header.elements.length; i ++ ) {
  225. const elementDesc = header.elements[ i ];
  226. const attributeMap = mapElementAttributes( elementDesc.properties );
  227. for ( let j = 0; j < elementDesc.count; j ++ ) {
  228. const element = parseASCIIElement( elementDesc.properties, tokens );
  229. if ( ! element ) break loop;
  230. handleElement( buffer, elementDesc.name, element, attributeMap );
  231. }
  232. }
  233. return postProcess( buffer );
  234. }
  235. function postProcess( buffer ) {
  236. let geometry = new BufferGeometry();
  237. // mandatory buffer data
  238. if ( buffer.indices.length > 0 ) {
  239. geometry.setIndex( buffer.indices );
  240. }
  241. geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
  242. // optional buffer data
  243. if ( buffer.normals.length > 0 ) {
  244. geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
  245. }
  246. if ( buffer.uvs.length > 0 ) {
  247. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
  248. }
  249. if ( buffer.colors.length > 0 ) {
  250. geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
  251. }
  252. if ( buffer.faceVertexUvs.length > 0 || buffer.faceVertexColors.length > 0 ) {
  253. geometry = geometry.toNonIndexed();
  254. if ( buffer.faceVertexUvs.length > 0 ) geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
  255. if ( buffer.faceVertexColors.length > 0 ) geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.faceVertexColors, 3 ) );
  256. }
  257. // custom buffer data
  258. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  259. if ( buffer[ customProperty ].length > 0 ) {
  260. geometry.setAttribute(
  261. customProperty,
  262. new Float32BufferAttribute(
  263. buffer[ customProperty ],
  264. scope.customPropertyMapping[ customProperty ].length
  265. )
  266. );
  267. }
  268. }
  269. geometry.computeBoundingSphere();
  270. return geometry;
  271. }
  272. function handleElement( buffer, elementName, element, cacheEntry ) {
  273. if ( elementName === 'vertex' ) {
  274. buffer.vertices.push( element[ cacheEntry.attrX ], element[ cacheEntry.attrY ], element[ cacheEntry.attrZ ] );
  275. if ( cacheEntry.attrNX !== null && cacheEntry.attrNY !== null && cacheEntry.attrNZ !== null ) {
  276. buffer.normals.push( element[ cacheEntry.attrNX ], element[ cacheEntry.attrNY ], element[ cacheEntry.attrNZ ] );
  277. }
  278. if ( cacheEntry.attrS !== null && cacheEntry.attrT !== null ) {
  279. buffer.uvs.push( element[ cacheEntry.attrS ], element[ cacheEntry.attrT ] );
  280. }
  281. if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
  282. _color.setRGB(
  283. element[ cacheEntry.attrR ] / 255.0,
  284. element[ cacheEntry.attrG ] / 255.0,
  285. element[ cacheEntry.attrB ] / 255.0,
  286. SRGBColorSpace
  287. );
  288. buffer.colors.push( _color.r, _color.g, _color.b );
  289. }
  290. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  291. for ( const elementProperty of scope.customPropertyMapping[ customProperty ] ) {
  292. buffer[ customProperty ].push( element[ elementProperty ] );
  293. }
  294. }
  295. } else if ( elementName === 'face' ) {
  296. const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  297. const texcoord = element.texcoord;
  298. if ( vertex_indices.length === 3 ) {
  299. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  300. if ( texcoord && texcoord.length === 6 ) {
  301. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  302. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  303. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  304. }
  305. } else if ( vertex_indices.length === 4 ) {
  306. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  307. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  308. }
  309. // face colors
  310. if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
  311. _color.setRGB(
  312. element[ cacheEntry.attrR ] / 255.0,
  313. element[ cacheEntry.attrG ] / 255.0,
  314. element[ cacheEntry.attrB ] / 255.0,
  315. SRGBColorSpace
  316. );
  317. buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
  318. buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
  319. buffer.faceVertexColors.push( _color.r, _color.g, _color.b );
  320. }
  321. }
  322. }
  323. function binaryReadElement( at, properties ) {
  324. const element = {};
  325. let read = 0;
  326. for ( let i = 0; i < properties.length; i ++ ) {
  327. const property = properties[ i ];
  328. const valueReader = property.valueReader;
  329. if ( property.type === 'list' ) {
  330. const list = [];
  331. const n = property.countReader.read( at + read );
  332. read += property.countReader.size;
  333. for ( let j = 0; j < n; j ++ ) {
  334. list.push( valueReader.read( at + read ) );
  335. read += valueReader.size;
  336. }
  337. element[ property.name ] = list;
  338. } else {
  339. element[ property.name ] = valueReader.read( at + read );
  340. read += valueReader.size;
  341. }
  342. }
  343. return [ element, read ];
  344. }
  345. function setPropertyBinaryReaders( properties, body, little_endian ) {
  346. function getBinaryReader( dataview, type, little_endian ) {
  347. switch ( type ) {
  348. // corespondences for non-specific length types here match rply:
  349. case 'int8': case 'char': return { read: ( at ) => {
  350. return dataview.getInt8( at );
  351. }, size: 1 };
  352. case 'uint8': case 'uchar': return { read: ( at ) => {
  353. return dataview.getUint8( at );
  354. }, size: 1 };
  355. case 'int16': case 'short': return { read: ( at ) => {
  356. return dataview.getInt16( at, little_endian );
  357. }, size: 2 };
  358. case 'uint16': case 'ushort': return { read: ( at ) => {
  359. return dataview.getUint16( at, little_endian );
  360. }, size: 2 };
  361. case 'int32': case 'int': return { read: ( at ) => {
  362. return dataview.getInt32( at, little_endian );
  363. }, size: 4 };
  364. case 'uint32': case 'uint': return { read: ( at ) => {
  365. return dataview.getUint32( at, little_endian );
  366. }, size: 4 };
  367. case 'float32': case 'float': return { read: ( at ) => {
  368. return dataview.getFloat32( at, little_endian );
  369. }, size: 4 };
  370. case 'float64': case 'double': return { read: ( at ) => {
  371. return dataview.getFloat64( at, little_endian );
  372. }, size: 8 };
  373. }
  374. }
  375. for ( let i = 0, l = properties.length; i < l; i ++ ) {
  376. const property = properties[ i ];
  377. if ( property.type === 'list' ) {
  378. property.countReader = getBinaryReader( body, property.countType, little_endian );
  379. property.valueReader = getBinaryReader( body, property.itemType, little_endian );
  380. } else {
  381. property.valueReader = getBinaryReader( body, property.type, little_endian );
  382. }
  383. }
  384. }
  385. function parseBinary( data, header ) {
  386. const buffer = createBuffer();
  387. const little_endian = ( header.format === 'binary_little_endian' );
  388. const body = new DataView( data, header.headerLength );
  389. let result, loc = 0;
  390. for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  391. const elementDesc = header.elements[ currentElement ];
  392. const properties = elementDesc.properties;
  393. const attributeMap = mapElementAttributes( properties );
  394. setPropertyBinaryReaders( properties, body, little_endian );
  395. for ( let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount ++ ) {
  396. result = binaryReadElement( loc, properties );
  397. loc += result[ 1 ];
  398. const element = result[ 0 ];
  399. handleElement( buffer, elementDesc.name, element, attributeMap );
  400. }
  401. }
  402. return postProcess( buffer );
  403. }
  404. function extractHeaderText( bytes ) {
  405. let i = 0;
  406. let cont = true;
  407. let line = '';
  408. const lines = [];
  409. const startLine = new TextDecoder().decode( bytes.subarray( 0, 5 ) );
  410. const hasCRNL = /^ply\r\n/.test( startLine );
  411. do {
  412. const c = String.fromCharCode( bytes[ i ++ ] );
  413. if ( c !== '\n' && c !== '\r' ) {
  414. line += c;
  415. } else {
  416. if ( line === 'end_header' ) cont = false;
  417. if ( line !== '' ) {
  418. lines.push( line );
  419. line = '';
  420. }
  421. }
  422. } while ( cont && i < bytes.length );
  423. // ascii section using \r\n as line endings
  424. if ( hasCRNL === true ) i ++;
  425. return { headerText: lines.join( '\r' ) + '\r', headerLength: i };
  426. }
  427. //
  428. let geometry;
  429. const scope = this;
  430. if ( data instanceof ArrayBuffer ) {
  431. const bytes = new Uint8Array( data );
  432. const { headerText, headerLength } = extractHeaderText( bytes );
  433. const header = parseHeader( headerText, headerLength );
  434. if ( header.format === 'ascii' ) {
  435. const text = new TextDecoder().decode( bytes );
  436. geometry = parseASCII( text, header );
  437. } else {
  438. geometry = parseBinary( data, header );
  439. }
  440. } else {
  441. geometry = parseASCII( data, parseHeader( data ) );
  442. }
  443. return geometry;
  444. }
  445. }
  446. class ArrayStream {
  447. constructor( arr ) {
  448. this.arr = arr;
  449. this.i = 0;
  450. }
  451. empty() {
  452. return this.i >= this.arr.length;
  453. }
  454. next() {
  455. return this.arr[ this.i ++ ];
  456. }
  457. }
  458. export { PLYLoader };
粤ICP备19079148号