MTLLoader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. import {
  2. Color,
  3. ColorManagement,
  4. DefaultLoadingManager,
  5. FileLoader,
  6. FrontSide,
  7. Loader,
  8. LoaderUtils,
  9. MeshPhongMaterial,
  10. RepeatWrapping,
  11. TextureLoader,
  12. Vector2,
  13. SRGBColorSpace
  14. } from 'three';
  15. /**
  16. * Loads a Wavefront .mtl file specifying materials
  17. */
  18. class MTLLoader extends Loader {
  19. constructor( manager ) {
  20. super( manager );
  21. }
  22. /**
  23. * Loads and parses a MTL asset from a URL.
  24. *
  25. * @param {string} url - URL to the MTL file.
  26. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  27. * @param {Function} [onProgress] - Callback for download progress.
  28. * @param {Function} [onError] - Callback for download errors.
  29. *
  30. * @see setPath setResourcePath
  31. *
  32. * @note In order for relative texture references to resolve correctly
  33. * you must call setResourcePath() explicitly prior to load.
  34. */
  35. load( url, onLoad, onProgress, onError ) {
  36. const scope = this;
  37. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  38. const loader = new FileLoader( this.manager );
  39. loader.setPath( this.path );
  40. loader.setRequestHeader( this.requestHeader );
  41. loader.setWithCredentials( this.withCredentials );
  42. loader.load( url, function ( text ) {
  43. try {
  44. onLoad( scope.parse( text, path ) );
  45. } catch ( e ) {
  46. if ( onError ) {
  47. onError( e );
  48. } else {
  49. console.error( e );
  50. }
  51. scope.manager.itemError( url );
  52. }
  53. }, onProgress, onError );
  54. }
  55. setMaterialOptions( value ) {
  56. this.materialOptions = value;
  57. return this;
  58. }
  59. /**
  60. * Parses a MTL file.
  61. *
  62. * @param {string} text - Content of MTL file
  63. * @param {string} path
  64. * @return {MaterialCreator}
  65. *
  66. * @see setPath setResourcePath
  67. *
  68. * @note In order for relative texture references to resolve correctly
  69. * you must call setResourcePath() explicitly prior to parse.
  70. */
  71. parse( text, path ) {
  72. const lines = text.split( '\n' );
  73. let info = {};
  74. const delimiter_pattern = /\s+/;
  75. const materialsInfo = {};
  76. for ( let i = 0; i < lines.length; i ++ ) {
  77. let line = lines[ i ];
  78. line = line.trim();
  79. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  80. // Blank line or comment ignore
  81. continue;
  82. }
  83. const pos = line.indexOf( ' ' );
  84. let key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  85. key = key.toLowerCase();
  86. let value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  87. value = value.trim();
  88. if ( key === 'newmtl' ) {
  89. // New material
  90. info = { name: value };
  91. materialsInfo[ value ] = info;
  92. } else {
  93. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  94. const ss = value.split( delimiter_pattern, 3 );
  95. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  96. } else {
  97. info[ key ] = value;
  98. }
  99. }
  100. }
  101. const materialCreator = new MaterialCreator( this.resourcePath || path, this.materialOptions );
  102. materialCreator.setCrossOrigin( this.crossOrigin );
  103. materialCreator.setManager( this.manager );
  104. materialCreator.setMaterials( materialsInfo );
  105. return materialCreator;
  106. }
  107. }
  108. /**
  109. * Create a new MTLLoader.MaterialCreator
  110. * @param baseUrl - Url relative to which textures are loaded
  111. * @param options - Set of options on how to construct the materials
  112. * side: Which side to apply the material
  113. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  114. * wrap: What type of wrapping to apply for textures
  115. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  116. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  117. * Default: false, assumed to be already normalized
  118. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  119. * Default: false
  120. * @constructor
  121. */
  122. class MaterialCreator {
  123. constructor( baseUrl = '', options = {} ) {
  124. this.baseUrl = baseUrl;
  125. this.options = options;
  126. this.materialsInfo = {};
  127. this.materials = {};
  128. this.materialsArray = [];
  129. this.nameLookup = {};
  130. this.crossOrigin = 'anonymous';
  131. this.side = ( this.options.side !== undefined ) ? this.options.side : FrontSide;
  132. this.wrap = ( this.options.wrap !== undefined ) ? this.options.wrap : RepeatWrapping;
  133. }
  134. setCrossOrigin( value ) {
  135. this.crossOrigin = value;
  136. return this;
  137. }
  138. setManager( value ) {
  139. this.manager = value;
  140. }
  141. setMaterials( materialsInfo ) {
  142. this.materialsInfo = this.convert( materialsInfo );
  143. this.materials = {};
  144. this.materialsArray = [];
  145. this.nameLookup = {};
  146. }
  147. convert( materialsInfo ) {
  148. if ( ! this.options ) return materialsInfo;
  149. const converted = {};
  150. for ( const mn in materialsInfo ) {
  151. // Convert materials info into normalized form based on options
  152. const mat = materialsInfo[ mn ];
  153. const covmat = {};
  154. converted[ mn ] = covmat;
  155. for ( const prop in mat ) {
  156. let save = true;
  157. let value = mat[ prop ];
  158. const lprop = prop.toLowerCase();
  159. switch ( lprop ) {
  160. case 'kd':
  161. case 'ka':
  162. case 'ks':
  163. // Diffuse color (color under white light) using RGB values
  164. if ( this.options && this.options.normalizeRGB ) {
  165. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  166. }
  167. if ( this.options && this.options.ignoreZeroRGBs ) {
  168. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  169. // ignore
  170. save = false;
  171. }
  172. }
  173. break;
  174. default:
  175. break;
  176. }
  177. if ( save ) {
  178. covmat[ lprop ] = value;
  179. }
  180. }
  181. }
  182. return converted;
  183. }
  184. preload() {
  185. for ( const mn in this.materialsInfo ) {
  186. this.create( mn );
  187. }
  188. }
  189. getIndex( materialName ) {
  190. return this.nameLookup[ materialName ];
  191. }
  192. getAsArray() {
  193. let index = 0;
  194. for ( const mn in this.materialsInfo ) {
  195. this.materialsArray[ index ] = this.create( mn );
  196. this.nameLookup[ mn ] = index;
  197. index ++;
  198. }
  199. return this.materialsArray;
  200. }
  201. create( materialName ) {
  202. if ( this.materials[ materialName ] === undefined ) {
  203. this.createMaterial_( materialName );
  204. }
  205. return this.materials[ materialName ];
  206. }
  207. createMaterial_( materialName ) {
  208. // Create material
  209. const scope = this;
  210. const mat = this.materialsInfo[ materialName ];
  211. const params = {
  212. name: materialName,
  213. side: this.side
  214. };
  215. function resolveURL( baseUrl, url ) {
  216. if ( typeof url !== 'string' || url === '' )
  217. return '';
  218. // Absolute URL
  219. if ( /^https?:\/\//i.test( url ) ) return url;
  220. return baseUrl + url;
  221. }
  222. function setMapForType( mapType, value ) {
  223. if ( params[ mapType ] ) return; // Keep the first encountered texture
  224. const texParams = scope.getTextureParams( value, params );
  225. const map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  226. map.repeat.copy( texParams.scale );
  227. map.offset.copy( texParams.offset );
  228. map.wrapS = scope.wrap;
  229. map.wrapT = scope.wrap;
  230. if ( mapType === 'map' || mapType === 'emissiveMap' ) {
  231. map.colorSpace = SRGBColorSpace;
  232. }
  233. params[ mapType ] = map;
  234. }
  235. for ( const prop in mat ) {
  236. const value = mat[ prop ];
  237. let n;
  238. if ( value === '' ) continue;
  239. switch ( prop.toLowerCase() ) {
  240. // Ns is material specular exponent
  241. case 'kd':
  242. // Diffuse color (color under white light) using RGB values
  243. params.color = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  244. break;
  245. case 'ks':
  246. // Specular color (color when light is reflected from shiny surface) using RGB values
  247. params.specular = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  248. break;
  249. case 'ke':
  250. // Emissive using RGB values
  251. params.emissive = ColorManagement.toWorkingColorSpace( new Color().fromArray( value ), SRGBColorSpace );
  252. break;
  253. case 'map_kd':
  254. // Diffuse texture map
  255. setMapForType( 'map', value );
  256. break;
  257. case 'map_ks':
  258. // Specular map
  259. setMapForType( 'specularMap', value );
  260. break;
  261. case 'map_ke':
  262. // Emissive map
  263. setMapForType( 'emissiveMap', value );
  264. break;
  265. case 'norm':
  266. setMapForType( 'normalMap', value );
  267. break;
  268. case 'map_bump':
  269. case 'bump':
  270. // Bump texture map
  271. setMapForType( 'bumpMap', value );
  272. break;
  273. case 'disp':
  274. // Displacement texture map
  275. setMapForType( 'displacementMap', value );
  276. break;
  277. case 'map_d':
  278. // Alpha map
  279. setMapForType( 'alphaMap', value );
  280. params.transparent = true;
  281. break;
  282. case 'ns':
  283. // The specular exponent (defines the focus of the specular highlight)
  284. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  285. params.shininess = parseFloat( value );
  286. break;
  287. case 'd':
  288. n = parseFloat( value );
  289. if ( n < 1 ) {
  290. params.opacity = n;
  291. params.transparent = true;
  292. }
  293. break;
  294. case 'tr':
  295. n = parseFloat( value );
  296. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  297. if ( n > 0 ) {
  298. params.opacity = 1 - n;
  299. params.transparent = true;
  300. }
  301. break;
  302. default:
  303. break;
  304. }
  305. }
  306. this.materials[ materialName ] = new MeshPhongMaterial( params );
  307. return this.materials[ materialName ];
  308. }
  309. getTextureParams( value, matParams ) {
  310. const texParams = {
  311. scale: new Vector2( 1, 1 ),
  312. offset: new Vector2( 0, 0 )
  313. };
  314. const items = value.split( /\s+/ );
  315. let pos;
  316. pos = items.indexOf( '-bm' );
  317. if ( pos >= 0 ) {
  318. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  319. items.splice( pos, 2 );
  320. }
  321. pos = items.indexOf( '-mm' );
  322. if ( pos >= 0 ) {
  323. matParams.displacementBias = parseFloat( items[ pos + 1 ] );
  324. matParams.displacementScale = parseFloat( items[ pos + 2 ] );
  325. items.splice( pos, 3 );
  326. }
  327. pos = items.indexOf( '-s' );
  328. if ( pos >= 0 ) {
  329. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  330. items.splice( pos, 4 ); // we expect 3 parameters here!
  331. }
  332. pos = items.indexOf( '-o' );
  333. if ( pos >= 0 ) {
  334. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  335. items.splice( pos, 4 ); // we expect 3 parameters here!
  336. }
  337. texParams.url = items.join( ' ' ).trim();
  338. return texParams;
  339. }
  340. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  341. const manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  342. let loader = manager.getHandler( url );
  343. if ( loader === null ) {
  344. loader = new TextureLoader( manager );
  345. }
  346. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  347. const texture = loader.load( url, onLoad, onProgress, onError );
  348. if ( mapping !== undefined ) texture.mapping = mapping;
  349. return texture;
  350. }
  351. }
  352. export { MTLLoader };
粤ICP备19079148号