MTLLoader.js 11 KB

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