MTLLoader.js 11 KB

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