MTLLoader.js 10 KB

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