MTLLoader.js 12 KB

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