PageRenderTime 804ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/js/loaders/PLYLoader.js

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