PLYLoader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. import {
  2. BufferGeometry,
  3. FileLoader,
  4. Float32BufferAttribute,
  5. Loader,
  6. LoaderUtils
  7. } from '../../../build/three.module.js';
  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. */
  33. class PLYLoader extends Loader {
  34. constructor( manager ) {
  35. super( manager );
  36. this.propertyNameMapping = {};
  37. }
  38. load( url, onLoad, onProgress, onError ) {
  39. const scope = this;
  40. const loader = new FileLoader( this.manager );
  41. loader.setPath( this.path );
  42. loader.setResponseType( 'arraybuffer' );
  43. loader.setRequestHeader( this.requestHeader );
  44. loader.setWithCredentials( this.withCredentials );
  45. loader.load( url, function ( text ) {
  46. try {
  47. onLoad( scope.parse( text ) );
  48. } catch ( e ) {
  49. if ( onError ) {
  50. onError( e );
  51. } else {
  52. console.error( e );
  53. }
  54. scope.manager.itemError( url );
  55. }
  56. }, onProgress, onError );
  57. }
  58. setPropertyNameMapping( mapping ) {
  59. this.propertyNameMapping = mapping;
  60. }
  61. parse( data ) {
  62. function parseHeader( data ) {
  63. const patternHeader = /ply([\s\S]*)end_header\r?\n/;
  64. let headerText = '';
  65. let headerLength = 0;
  66. const result = patternHeader.exec( data );
  67. if ( result !== null ) {
  68. headerText = result[ 1 ];
  69. headerLength = new Blob( [ result[ 0 ] ] ).size;
  70. }
  71. const header = {
  72. comments: [],
  73. elements: [],
  74. headerLength: headerLength,
  75. objInfo: ''
  76. };
  77. const lines = headerText.split( '\n' );
  78. let currentElement;
  79. function make_ply_element_property( propertValues, propertyNameMapping ) {
  80. const property = { type: propertValues[ 0 ] };
  81. if ( property.type === 'list' ) {
  82. property.name = propertValues[ 3 ];
  83. property.countType = propertValues[ 1 ];
  84. property.itemType = propertValues[ 2 ];
  85. } else {
  86. property.name = propertValues[ 1 ];
  87. }
  88. if ( property.name in propertyNameMapping ) {
  89. property.name = propertyNameMapping[ property.name ];
  90. }
  91. return property;
  92. }
  93. for ( let i = 0; i < lines.length; i ++ ) {
  94. let line = lines[ i ];
  95. line = line.trim();
  96. if ( line === '' ) continue;
  97. const lineValues = line.split( /\s+/ );
  98. const lineType = lineValues.shift();
  99. line = lineValues.join( ' ' );
  100. switch ( lineType ) {
  101. case 'format':
  102. header.format = lineValues[ 0 ];
  103. header.version = lineValues[ 1 ];
  104. break;
  105. case 'comment':
  106. header.comments.push( line );
  107. break;
  108. case 'element':
  109. if ( currentElement !== undefined ) {
  110. header.elements.push( currentElement );
  111. }
  112. currentElement = {};
  113. currentElement.name = lineValues[ 0 ];
  114. currentElement.count = parseInt( lineValues[ 1 ] );
  115. currentElement.properties = [];
  116. break;
  117. case 'property':
  118. currentElement.properties.push( make_ply_element_property( lineValues, scope.propertyNameMapping ) );
  119. break;
  120. case 'obj_info':
  121. header.objInfo = line;
  122. break;
  123. default:
  124. console.log( 'unhandled', lineType, lineValues );
  125. }
  126. }
  127. if ( currentElement !== undefined ) {
  128. header.elements.push( currentElement );
  129. }
  130. return header;
  131. }
  132. function parseASCIINumber( n, type ) {
  133. switch ( type ) {
  134. case 'char': case 'uchar': case 'short': case 'ushort': case 'int': case 'uint':
  135. case 'int8': case 'uint8': case 'int16': case 'uint16': case 'int32': case 'uint32':
  136. return parseInt( n );
  137. case 'float': case 'double': case 'float32': case 'float64':
  138. return parseFloat( n );
  139. }
  140. }
  141. function parseASCIIElement( properties, line ) {
  142. const values = line.split( /\s+/ );
  143. const element = {};
  144. for ( let i = 0; i < properties.length; i ++ ) {
  145. if ( properties[ i ].type === 'list' ) {
  146. const list = [];
  147. const n = parseASCIINumber( values.shift(), properties[ i ].countType );
  148. for ( let j = 0; j < n; j ++ ) {
  149. list.push( parseASCIINumber( values.shift(), properties[ i ].itemType ) );
  150. }
  151. element[ properties[ i ].name ] = list;
  152. } else {
  153. element[ properties[ i ].name ] = parseASCIINumber( values.shift(), properties[ i ].type );
  154. }
  155. }
  156. return element;
  157. }
  158. function parseASCII( data, header ) {
  159. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  160. const buffer = {
  161. indices: [],
  162. vertices: [],
  163. normals: [],
  164. uvs: [],
  165. faceVertexUvs: [],
  166. colors: []
  167. };
  168. let result;
  169. const patternBody = /end_header\s([\s\S]*)$/;
  170. let body = '';
  171. if ( ( result = patternBody.exec( data ) ) !== null ) {
  172. body = result[ 1 ];
  173. }
  174. const lines = body.split( '\n' );
  175. let currentElement = 0;
  176. let currentElementCount = 0;
  177. for ( let i = 0; i < lines.length; i ++ ) {
  178. let line = lines[ i ];
  179. line = line.trim();
  180. if ( line === '' ) {
  181. continue;
  182. }
  183. if ( currentElementCount >= header.elements[ currentElement ].count ) {
  184. currentElement ++;
  185. currentElementCount = 0;
  186. }
  187. const element = parseASCIIElement( header.elements[ currentElement ].properties, line );
  188. handleElement( buffer, header.elements[ currentElement ].name, element );
  189. currentElementCount ++;
  190. }
  191. return postProcess( buffer );
  192. }
  193. function postProcess( buffer ) {
  194. let geometry = new BufferGeometry();
  195. // mandatory buffer data
  196. if ( buffer.indices.length > 0 ) {
  197. geometry.setIndex( buffer.indices );
  198. }
  199. geometry.setAttribute( 'position', new Float32BufferAttribute( buffer.vertices, 3 ) );
  200. // optional buffer data
  201. if ( buffer.normals.length > 0 ) {
  202. geometry.setAttribute( 'normal', new Float32BufferAttribute( buffer.normals, 3 ) );
  203. }
  204. if ( buffer.uvs.length > 0 ) {
  205. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.uvs, 2 ) );
  206. }
  207. if ( buffer.colors.length > 0 ) {
  208. geometry.setAttribute( 'color', new Float32BufferAttribute( buffer.colors, 3 ) );
  209. }
  210. if ( buffer.faceVertexUvs.length > 0 ) {
  211. geometry = geometry.toNonIndexed();
  212. geometry.setAttribute( 'uv', new Float32BufferAttribute( buffer.faceVertexUvs, 2 ) );
  213. }
  214. geometry.computeBoundingSphere();
  215. return geometry;
  216. }
  217. function handleElement( buffer, elementName, element ) {
  218. function findAttrName( names ) {
  219. for ( let i = 0, l = names.length; i < l; i ++ ) {
  220. const name = names[ i ];
  221. if ( name in element ) return name;
  222. }
  223. return null;
  224. }
  225. const attrX = findAttrName( [ 'x', 'px', 'posx' ] ) || 'x';
  226. const attrY = findAttrName( [ 'y', 'py', 'posy' ] ) || 'y';
  227. const attrZ = findAttrName( [ 'z', 'pz', 'posz' ] ) || 'z';
  228. const attrNX = findAttrName( [ 'nx', 'normalx' ] );
  229. const attrNY = findAttrName( [ 'ny', 'normaly' ] );
  230. const attrNZ = findAttrName( [ 'nz', 'normalz' ] );
  231. const attrS = findAttrName( [ 's', 'u', 'texture_u', 'tx' ] );
  232. const attrT = findAttrName( [ 't', 'v', 'texture_v', 'ty' ] );
  233. const attrR = findAttrName( [ 'red', 'diffuse_red', 'r', 'diffuse_r' ] );
  234. const attrG = findAttrName( [ 'green', 'diffuse_green', 'g', 'diffuse_g' ] );
  235. const attrB = findAttrName( [ 'blue', 'diffuse_blue', 'b', 'diffuse_b' ] );
  236. if ( elementName === 'vertex' ) {
  237. buffer.vertices.push( element[ attrX ], element[ attrY ], element[ attrZ ] );
  238. if ( attrNX !== null && attrNY !== null && attrNZ !== null ) {
  239. buffer.normals.push( element[ attrNX ], element[ attrNY ], element[ attrNZ ] );
  240. }
  241. if ( attrS !== null && attrT !== null ) {
  242. buffer.uvs.push( element[ attrS ], element[ attrT ] );
  243. }
  244. if ( attrR !== null && attrG !== null && attrB !== null ) {
  245. buffer.colors.push( element[ attrR ] / 255.0, element[ attrG ] / 255.0, element[ attrB ] / 255.0 );
  246. }
  247. } else if ( elementName === 'face' ) {
  248. const vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  249. const texcoord = element.texcoord;
  250. if ( vertex_indices.length === 3 ) {
  251. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 2 ] );
  252. if ( texcoord && texcoord.length === 6 ) {
  253. buffer.faceVertexUvs.push( texcoord[ 0 ], texcoord[ 1 ] );
  254. buffer.faceVertexUvs.push( texcoord[ 2 ], texcoord[ 3 ] );
  255. buffer.faceVertexUvs.push( texcoord[ 4 ], texcoord[ 5 ] );
  256. }
  257. } else if ( vertex_indices.length === 4 ) {
  258. buffer.indices.push( vertex_indices[ 0 ], vertex_indices[ 1 ], vertex_indices[ 3 ] );
  259. buffer.indices.push( vertex_indices[ 1 ], vertex_indices[ 2 ], vertex_indices[ 3 ] );
  260. }
  261. }
  262. }
  263. function binaryRead( dataview, at, type, little_endian ) {
  264. switch ( type ) {
  265. // corespondences for non-specific length types here match rply:
  266. case 'int8': case 'char': return [ dataview.getInt8( at ), 1 ];
  267. case 'uint8': case 'uchar': return [ dataview.getUint8( at ), 1 ];
  268. case 'int16': case 'short': return [ dataview.getInt16( at, little_endian ), 2 ];
  269. case 'uint16': case 'ushort': return [ dataview.getUint16( at, little_endian ), 2 ];
  270. case 'int32': case 'int': return [ dataview.getInt32( at, little_endian ), 4 ];
  271. case 'uint32': case 'uint': return [ dataview.getUint32( at, little_endian ), 4 ];
  272. case 'float32': case 'float': return [ dataview.getFloat32( at, little_endian ), 4 ];
  273. case 'float64': case 'double': return [ dataview.getFloat64( at, little_endian ), 8 ];
  274. }
  275. }
  276. function binaryReadElement( dataview, at, properties, little_endian ) {
  277. const element = {};
  278. let result, read = 0;
  279. for ( let i = 0; i < properties.length; i ++ ) {
  280. if ( properties[ i ].type === 'list' ) {
  281. const list = [];
  282. result = binaryRead( dataview, at + read, properties[ i ].countType, little_endian );
  283. const n = result[ 0 ];
  284. read += result[ 1 ];
  285. for ( let j = 0; j < n; j ++ ) {
  286. result = binaryRead( dataview, at + read, properties[ i ].itemType, little_endian );
  287. list.push( result[ 0 ] );
  288. read += result[ 1 ];
  289. }
  290. element[ properties[ i ].name ] = list;
  291. } else {
  292. result = binaryRead( dataview, at + read, properties[ i ].type, little_endian );
  293. element[ properties[ i ].name ] = result[ 0 ];
  294. read += result[ 1 ];
  295. }
  296. }
  297. return [ element, read ];
  298. }
  299. function parseBinary( data, header ) {
  300. const buffer = {
  301. indices: [],
  302. vertices: [],
  303. normals: [],
  304. uvs: [],
  305. faceVertexUvs: [],
  306. colors: []
  307. };
  308. const little_endian = ( header.format === 'binary_little_endian' );
  309. const body = new DataView( data, header.headerLength );
  310. let result, loc = 0;
  311. for ( let currentElement = 0; currentElement < header.elements.length; currentElement ++ ) {
  312. for ( let currentElementCount = 0; currentElementCount < header.elements[ currentElement ].count; currentElementCount ++ ) {
  313. result = binaryReadElement( body, loc, header.elements[ currentElement ].properties, little_endian );
  314. loc += result[ 1 ];
  315. const element = result[ 0 ];
  316. handleElement( buffer, header.elements[ currentElement ].name, element );
  317. }
  318. }
  319. return postProcess( buffer );
  320. }
  321. //
  322. let geometry;
  323. const scope = this;
  324. if ( data instanceof ArrayBuffer ) {
  325. const text = LoaderUtils.decodeText( new Uint8Array( data ) );
  326. const header = parseHeader( text );
  327. geometry = header.format === 'ascii' ? parseASCII( text, header ) : parseBinary( data, header );
  328. } else {
  329. geometry = parseASCII( data, parseHeader( data ) );
  330. }
  331. return geometry;
  332. }
  333. }
  334. export { PLYLoader };