PLYLoader.js 17 KB

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