MTLLoader.js 11 KB

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