MTLLoader.js 10 KB

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