MTLLoader.js 10 KB

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