MTLLoader.js 11 KB

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