MTLLoader.js 11 KB

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