PLYLoader.js 16 KB

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