MTLLoader.js 10 KB

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