PLYLoader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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 setCustomPropertyMapping 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.setCustomPropertyMapping( {
  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 ) {
  78. const patternHeader = /^ply([\s\S]*)end_header(\r\n|\r|\n)/;
  79. let headerText = '';
  80. let headerLength = 0;
  81. const result = patternHeader.exec( data );
  82. if ( result !== null ) {
  83. headerText = result[ 1 ];
  84. headerLength = new Blob( [ result[ 0 ] ] ).size;
  85. }
  86. const header = {
  87. comments: [],
  88. elements: [],
  89. headerLength: headerLength,
  90. objInfo: ''
  91. };
  92. const lines = headerText.split( /\r\n|\r|\n/ );
  93. let currentElement;
  94. function make_ply_element_property( propertValues, propertyNameMapping ) {
  95. const property = { type: propertValues[ 0 ] };
  96. if ( property.type === 'list' ) {
  97. property.name = propertValues[ 3 ];
  98. property.countType = propertValues[ 1 ];
  99. property.itemType = propertValues[ 2 ];
  100. } else {
  101. property.name = propertValues[ 1 ];
  102. }
  103. if ( property.name in propertyNameMapping ) {
  104. property.name = propertyNameMapping[ property.name ];
  105. }
  106. return property;
  107. }
  108. for ( let i = 0; i < lines.length; i ++ ) {
  109. let line = lines[ i ];
  110. line = line.trim();
  111. if ( line === '' ) continue;
  112. const lineValues = line.split( /\s+/ );
  113. const lineType = lineValues.shift();
  114. line = lineValues.join( ' ' );
  115. switch ( lineType ) {
  116. case 'format':
  117. header.format = lineValues[ 0 ];
  118. header.version = lineValues[ 1 ];
  119. break;
  120. case 'comment':
  121. header.comments.push( line );
  122. break;
  123. case 'element':
  124. if ( currentElement !== undefined ) {
  125. header.elements.push( currentElement );
  126. }
  127. currentElement = {};
  128. currentElement.name = lineValues[ 0 ];
  129. currentElement.count = parseInt( lineValues[ 1 ] );
  130. currentElement.properties = [];
  131. break;
  132. case 'property':
  133. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  134. break;
  135. case 'obj_info':
  136. header.objInfo = line;
  137. break;
  138. default:
  139. console.log( 'unhandled', lineType, lineValues );
  140. }
  141. }
  142. if ( currentElement !== undefined ) {
  143. header.elements.push( currentElement );
  144. }
  145. return header;
  146. }
  147. function parseASCIINumber( n, type ) {
  148. switch ( type ) {
  149. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  150. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  151. return parseInt( n );
  152. case 'float': case 'double': case 'float32': case 'float64':
  153. return parseFloat( n );
  154. }
  155. }
  156. function parseASCIIElement( properties, line ) {
  157. const values = line.split( /\s+/ );
  158. const element = {};
  159. for ( let i = 0; i < properties.length; i ++ ) {
  160. if ( properties[ i ].type === 'list' ) {
  161. const list = [];
  162. const n = parseASCIINumber( values.shift(), properties[ i ].countType );
  163. for ( let j = 0; j < n; j ++ ) {
  164. list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) );
  165. }
  166. element[ properties[ i ].name ] = list;
  167. } else {
  168. element[ properties[ i ].name ] = parseASCIINumber( values.shift(), 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. };
  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 => { return property.name } );
  189. function findAttrName( names ) {
  190. for ( let i = 0, l = names.length; i < l; i ++ ) {
  191. const name = names[ i ];
  192. if ( name in elementNames ) return name;
  193. }
  194. return null;
  195. }
  196. return {
  197. attrX: findAttrName( [ 'x', 'px', 'posx' ] ) || 'x',
  198. attrY: findAttrName( [ 'y', 'py', 'posy' ] ) || 'y',
  199. attrZ: findAttrName( [ 'z', 'pz', 'posz' ] ) || 'z',
  200. attrNX: findAttrName( [ 'nx', 'normalx' ] ),
  201. attrNY: findAttrName( [ 'ny', 'normaly' ] ),
  202. attrNZ: findAttrName( [ 'nz', 'normalz' ] ),
  203. attrS: findAttrName( [ 's', 'u', 'texture_u', 'tx' ] ),
  204. attrT: findAttrName( [ 't', 'v', 'texture_v', 'ty' ] ),
  205. attrR: findAttrName( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] ),
  206. attrG: findAttrName( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] ),
  207. attrB: findAttrName( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] ),
  208. };
  209. }
  210. function parseASCII( data, header ) {
  211. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  212. const buffer = createBuffer();
  213. let result;
  214. const patternBody = /end_header\s([\s\S]*)$/;
  215. let body = '';
  216. if ( ( result = patternBody.exec( data ) ) !== null ) {
  217. body = result[ 1 ];
  218. }
  219. const lines = body.split( /\r\n|\r|\n/ );
  220. let currentElement = 0;
  221. let currentElementCount = 0;
  222. let elementDesc = header.elements[ currentElement ];
  223. let attributeMap = mapElementAttributes( elementDesc.properties );
  224. for ( let i = 0; i < lines.length; i ++ ) {
  225. let line = lines[ i ];
  226. line = line.trim();
  227. if ( line === '' ) {
  228. continue;
  229. }
  230. if ( currentElementCount >= elementDesc.count ) {
  231. currentElement ++;
  232. currentElementCount = 0;
  233. elementDesc = header.elements[ currentElement ];
  234. attributeMap = mapElementAttributes( elementDesc.properties );
  235. }
  236. const element = parseASCIIElement( elementDesc.properties, line );
  237. handleElement( buffer, elementDesc.name, element, attributeMap );
  238. currentElementCount ++;
  239. }
  240. return postProcess( buffer );
  241. }
  242. function postProcess( buffer ) {
  243. let geometry = new BufferGeometry();
  244. // mandatory buffer data
  245. if ( buffer.indices.length > 0 ) {
  246. geometry.setIndex( buffer.indices );
  247. }
  248. geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
  249. // optional buffer data
  250. if ( buffer.normals.length > 0 ) {
  251. geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
  252. }
  253. if ( buffer.uvs.length > 0 ) {
  254. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
  255. }
  256. if ( buffer.colors.length > 0 ) {
  257. geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
  258. }
  259. if ( buffer.faceVertexUvs.length > 0 ) {
  260. geometry = geometry.toNonIndexed();
  261. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
  262. }
  263. // custom buffer data
  264. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  265. if ( buffer[ customProperty ].length > 0 ) {
  266. geometry.setAttribute(
  267. customProperty,
  268. new Float32BufferAttribute(
  269. buffer[ customProperty ],
  270. scope.customPropertyMapping[ customProperty ].length
  271. )
  272. );
  273. }
  274. }
  275. geometry.computeBoundingSphere();
  276. return geometry;
  277. }
  278. function handleElement( buffer, elementName, element, cacheEntry ) {
  279. if ( elementName === 'vertex' ) {
  280. buffer.vertices.push( element[ cacheEntry.attrX ], element[ cacheEntry.attrY ], element[ cacheEntry.attrZ ] );
  281. if ( cacheEntry.attrNX !== null && cacheEntry.attrNY !== null && cacheEntry.attrNZ !== null ) {
  282. buffer.normals.push( element[ cacheEntry.attrNX ], element[ cacheEntry.attrNY ], element[ cacheEntry.attrNZ ] );
  283. }
  284. if ( cacheEntry.attrS !== null && cacheEntry.attrT !== null ) {
  285. buffer.uvs.push( element[ cacheEntry.attrS ], element[ cacheEntry.attrT ] );
  286. }
  287. if ( cacheEntry.attrR !== null && cacheEntry.attrG !== null && cacheEntry.attrB !== null ) {
  288. _color.setRGB(
  289. element[ cacheEntry.attrR ] / 255.0,
  290. element[ cacheEntry.attrG ] / 255.0,
  291. element[ cacheEntry.attrB ] / 255.0
  292. ).convertSRGBToLinear();
  293. buffer.colors.push( _color.r, _color.g, _color.b );
  294. }
  295. for ( const customProperty of Object.keys( scope.customPropertyMapping ) ) {
  296. for ( const elementProperty of scope.customPropertyMapping[ customProperty ] ) {
  297. buffer[ customProperty ].push( element[ elementProperty ] );
  298. }
  299. }
  300. } else if ( elementName === 'face' ) {
  301. const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  302. const texcoord = element.texcoord;
  303. if ( vertex_indices.length === 3 ) {
  304. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  305. if ( texcoord && texcoord.length === 6 ) {
  306. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  307. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  308. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  309. }
  310. } else if ( vertex_indices.length === 4 ) {
  311. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  312. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  313. }
  314. }
  315. }
  316. function binaryRead( dataview, at, type, little_endian ) {
  317. switch ( type ) {
  318. // corespondences for non-specific length types here match rply:
  319. case 'int8': case 'char': return [ dataview.getInt8( at ), 1 ];
  320. case 'uint8': case 'uchar': return [ dataview.getUint8( at ), 1 ];
  321. case 'int16': case 'short': return [ dataview.getInt16( at, little_endian ), 2 ];
  322. case 'uint16': case 'ushort': return [ dataview.getUint16( at, little_endian ), 2 ];
  323. case 'int32': case 'int': return [ dataview.getInt32( at, little_endian ), 4 ];
  324. case 'uint32': case 'uint': return [ dataview.getUint32( at, little_endian ), 4 ];
  325. case 'float32': case 'float': return [ dataview.getFloat32( at, little_endian ), 4 ];
  326. case 'float64': case 'double': return [ dataview.getFloat64( at, little_endian ), 8 ];
  327. }
  328. }
  329. function binaryReadElement( dataview, at, properties, little_endian ) {
  330. const element = {};
  331. let result, read = 0;
  332. for ( let i = 0; i < properties.length; i ++ ) {
  333. if ( properties[ i ].type === 'list' ) {
  334. const list = [];
  335. result = binaryRead( dataview, at + read, properties[ i ].countType, little_endian );
  336. const n = result[ 0 ];
  337. read += result[ 1 ];
  338. for ( let j = 0; j < n; j ++ ) {
  339. result = binaryRead( dataview, at + read, properties[ i ].itemType, little_endian );
  340. list.push( result[ 0 ] );
  341. read += result[ 1 ];
  342. }
  343. element[ properties[ i ].name ] = list;
  344. } else {
  345. result = binaryRead( dataview, at + read, properties[ i ].type, little_endian );
  346. element[ properties[ i ].name ] = result[ 0 ];
  347. read += result[ 1 ];
  348. }
  349. }
  350. return [ element, read ];
  351. }
  352. function parseBinary( data, header ) {
  353. const buffer = createBuffer();
  354. const little_endian = ( header.format === 'binary_little_endian' );
  355. const body = new DataView( data, header.headerLength );
  356. let result, loc = 0;
  357. for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  358. const elementDesc = header.elements[ currentElement ];
  359. const attributeMap = mapElementAttributes( elementDesc.properties );
  360. for ( let currentElementCount = 0; currentElementCount < elementDesc.count; currentElementCount ++ ) {
  361. result = binaryReadElement( body, loc, elementDesc.properties, little_endian );
  362. loc += result[ 1 ];
  363. const element = result[ 0 ];
  364. handleElement( buffer, elementDesc.name, element, attributeMap );
  365. }
  366. }
  367. return postProcess( buffer );
  368. }
  369. function extractHeaderText( bytes ) {
  370. let i = 0;
  371. let cont = true;
  372. let line = '';
  373. const lines = [];
  374. do {
  375. const c = String.fromCharCode( bytes[ i++ ] );
  376. if ( c !== "\n" && c !== "\r" ) {
  377. line += c;
  378. } else {
  379. if ( line === 'end_header' ) cont = false;
  380. if ( line !== '' ) {
  381. lines.push( line );
  382. line = '';
  383. }
  384. }
  385. } while ( cont && i < bytes.length );
  386. return lines.join( "\r" ) + "\r";
  387. }
  388. //
  389. let geometry;
  390. const scope = this;
  391. if ( data instanceof ArrayBuffer ) {
  392. const bytes = new Uint8Array( data );
  393. const headerText = extractHeaderText( bytes );
  394. const header = parseHeader( headerText );
  395. if ( header.format === 'ascii' ) {
  396. const text = new TextDecoder().decode( bytes );
  397. geometry = parseASCII( text, header );
  398. } else {
  399. geometry = parseBinary( data, header );
  400. }
  401. } else {
  402. geometry = parseASCII( data, parseHeader( data ) );
  403. }
  404. return geometry;
  405. }
  406. }
  407. export { PLYLoader };