MTLLoader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. class MTLLoader extends Loader {
  17. constructor( manager ) {
  18. super( manager );
  19. }
  20. /**
  21. * Loads and parses a MTL asset from a URL.
  22. *
  23. * @param {String} url - URL to the MTL file.
  24. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  25. * @param {Function} [onProgress] - Callback for download progress.
  26. * @param {Function} [onError] - Callback for download errors.
  27. *
  28. * @see setPath setResourcePath
  29. *
  30. * @note In order for relative texture references to resolve correctly
  31. * you must call setResourcePath() explicitly prior to load.
  32. */
  33. load( url, onLoad, onProgress, onError ) {
  34. const scope = this;
  35. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  36. const loader = new FileLoader( this.manager );
  37. loader.setPath( this.path );
  38. loader.setRequestHeader( this.requestHeader );
  39. loader.setWithCredentials( this.withCredentials );
  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( 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 {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( text, path ) {
  69. const lines = text.split( '\n' );
  70. let info = {};
  71. const delimiter_pattern = /\s+/;
  72. const materialsInfo = {};
  73. for ( let i = 0; i < lines.length; i ++ ) {
  74. let 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. const pos = line.indexOf( ' ' );
  81. let key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  82. key = key.toLowerCase();
  83. let 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. const 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. const materialCreator = new 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. class MaterialCreator {
  120. constructor( baseUrl = '', options = {} ) {
  121. this.baseUrl = baseUrl;
  122. this.options = options;
  123. this.materialsInfo = {};
  124. this.materials = {};
  125. this.materialsArray = [];
  126. this.nameLookup = {};
  127. this.crossOrigin = 'anonymous';
  128. this.side = ( this.options.side !== undefined ) ? this.options.side : FrontSide;
  129. this.wrap = ( this.options.wrap !== undefined ) ? this.options.wrap : RepeatWrapping;
  130. }
  131. setCrossOrigin( value ) {
  132. this.crossOrigin = value;
  133. return this;
  134. }
  135. setManager( value ) {
  136. this.manager = value;
  137. }
  138. setMaterials( materialsInfo ) {
  139. this.materialsInfo = this.convert( materialsInfo );
  140. this.materials = {};
  141. this.materialsArray = [];
  142. this.nameLookup = {};
  143. }
  144. convert( materialsInfo ) {
  145. if ( ! this.options ) return materialsInfo;
  146. const converted = {};
  147. for ( const mn in materialsInfo ) {
  148. // Convert materials info into normalized form based on options
  149. const mat = materialsInfo[ mn ];
  150. const covmat = {};
  151. converted[ mn ] = covmat;
  152. for ( const prop in mat ) {
  153. let save = true;
  154. let value = mat[ prop ];
  155. const lprop = prop.toLowerCase();
  156. switch ( lprop ) {
  157. case 'kd':
  158. case 'ka':
  159. case 'ks':
  160. // Diffuse color (color under white light) using RGB values
  161. if ( this.options && this.options.normalizeRGB ) {
  162. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  163. }
  164. if ( this.options && this.options.ignoreZeroRGBs ) {
  165. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  166. // ignore
  167. save = false;
  168. }
  169. }
  170. break;
  171. default:
  172. break;
  173. }
  174. if ( save ) {
  175. covmat[ lprop ] = value;
  176. }
  177. }
  178. }
  179. return converted;
  180. }
  181. preload() {
  182. for ( const mn in this.materialsInfo ) {
  183. this.create( mn );
  184. }
  185. }
  186. getIndex( materialName ) {
  187. return this.nameLookup[ materialName ];
  188. }
  189. getAsArray() {
  190. let index = 0;
  191. for ( const mn in this.materialsInfo ) {
  192. this.materialsArray[ index ] = this.create( mn );
  193. this.nameLookup[ mn ] = index;
  194. index ++;
  195. }
  196. return this.materialsArray;
  197. }
  198. create( materialName ) {
  199. if ( this.materials[ materialName ] === undefined ) {
  200. this.createMaterial_( materialName );
  201. }
  202. return this.materials[ materialName ];
  203. }
  204. createMaterial_( materialName ) {
  205. // Create material
  206. const scope = this;
  207. const mat = this.materialsInfo[ materialName ];
  208. const params = {
  209. name: materialName,
  210. side: this.side
  211. };
  212. function resolveURL( baseUrl, url ) {
  213. if ( typeof url !== 'string' || url === '' )
  214. return '';
  215. // Absolute URL
  216. if ( /^https?:\/\//i.test( url ) ) return url;
  217. return baseUrl + url;
  218. }
  219. function setMapForType( mapType, value ) {
  220. if ( params[ mapType ] ) return; // Keep the first encountered texture
  221. const texParams = scope.getTextureParams( value, params );
  222. const map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  223. map.repeat.copy( texParams.scale );
  224. map.offset.copy( texParams.offset );
  225. map.wrapS = scope.wrap;
  226. map.wrapT = scope.wrap;
  227. params[ mapType ] = map;
  228. }
  229. for ( const prop in mat ) {
  230. const value = mat[ prop ];
  231. let n;
  232. if ( value === '' ) continue;
  233. switch ( prop.toLowerCase() ) {
  234. // Ns is material specular exponent
  235. case 'kd':
  236. // Diffuse color (color under white light) using RGB values
  237. params.color = new Color().fromArray( value );
  238. break;
  239. case 'ks':
  240. // Specular color (color when light is reflected from shiny surface) using RGB values
  241. params.specular = new Color().fromArray( value );
  242. break;
  243. case 'ke':
  244. // Emissive using RGB values
  245. params.emissive = new Color().fromArray( value );
  246. break;
  247. case 'map_kd':
  248. // Diffuse texture map
  249. setMapForType( 'map', value );
  250. break;
  251. case 'map_ks':
  252. // Specular map
  253. setMapForType( 'specularMap', value );
  254. break;
  255. case 'map_ke':
  256. // Emissive map
  257. setMapForType( 'emissiveMap', value );
  258. break;
  259. case 'norm':
  260. setMapForType( 'normalMap', value );
  261. break;
  262. case 'map_bump':
  263. case 'bump':
  264. // Bump texture map
  265. setMapForType( 'bumpMap', value );
  266. break;
  267. case 'map_d':
  268. // Alpha map
  269. setMapForType( 'alphaMap', value );
  270. params.transparent = true;
  271. break;
  272. case 'ns':
  273. // The specular exponent (defines the focus of the specular highlight)
  274. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  275. params.shininess = parseFloat( value );
  276. break;
  277. case 'd':
  278. n = parseFloat( value );
  279. if ( n < 1 ) {
  280. params.opacity = n;
  281. params.transparent = true;
  282. }
  283. break;
  284. case 'tr':
  285. n = parseFloat( value );
  286. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  287. if ( n > 0 ) {
  288. params.opacity = 1 - n;
  289. params.transparent = true;
  290. }
  291. break;
  292. default:
  293. break;
  294. }
  295. }
  296. this.materials[ materialName ] = new MeshPhongMaterial( params );
  297. return this.materials[ materialName ];
  298. }
  299. getTextureParams( value, matParams ) {
  300. const texParams = {
  301. scale: new Vector2( 1, 1 ),
  302. offset: new Vector2( 0, 0 )
  303. };
  304. const items = value.split( /\s+/ );
  305. let pos;
  306. pos = items.indexOf( '-bm' );
  307. if ( pos >= 0 ) {
  308. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  309. items.splice( pos, 2 );
  310. }
  311. pos = items.indexOf( '-s' );
  312. if ( pos >= 0 ) {
  313. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  314. items.splice( pos, 4 ); // we expect 3 parameters here!
  315. }
  316. pos = items.indexOf( '-o' );
  317. if ( pos >= 0 ) {
  318. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  319. items.splice( pos, 4 ); // we expect 3 parameters here!
  320. }
  321. texParams.url = items.join( ' ' ).trim();
  322. return texParams;
  323. }
  324. loadTexture( url, mapping, onLoad, onProgress, onError ) {
  325. const manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  326. let loader = manager.getHandler( url );
  327. if ( loader === null ) {
  328. loader = new TextureLoader( manager );
  329. }
  330. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  331. const texture = loader.load( url, onLoad, onProgress, onError );
  332. if ( mapping !== undefined ) texture.mapping = mapping;
  333. return texture;
  334. }
  335. }
  336. export { MTLLoader };