MTLLoader.js 11 KB

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