MTLLoader.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /**
  2. * Loads a Wavefront .mtl file specifying materials
  3. *
  4. * @author angelxuanchang
  5. */
  6. THREE.MTLLoader = function( baseUrl, options, crossOrigin ) {
  7. this.baseUrl = baseUrl;
  8. this.options = options;
  9. this.crossOrigin = crossOrigin;
  10. };
  11. THREE.MTLLoader.prototype = {
  12. constructor: THREE.MTLLoader,
  13. load: function ( url, onLoad, onProgress, onError ) {
  14. var scope = this;
  15. var loader = new THREE.XHRLoader();
  16. loader.setCrossOrigin( this.crossOrigin );
  17. loader.load( url, function ( text ) {
  18. onLoad( scope.parse( text ) );
  19. }, onProgress, onError );
  20. },
  21. /**
  22. * Parses loaded MTL file
  23. * @param text - Content of MTL file
  24. * @return {THREE.MTLLoader.MaterialCreator}
  25. */
  26. parse: function ( text ) {
  27. var lines = text.split( "\n" );
  28. var info = {};
  29. var delimiter_pattern = /\s+/;
  30. var materialsInfo = {};
  31. for ( var i = 0; i < lines.length; i ++ ) {
  32. var line = lines[ i ];
  33. line = line.trim();
  34. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  35. // Blank line or comment ignore
  36. continue;
  37. }
  38. var pos = line.indexOf( ' ' );
  39. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  40. key = key.toLowerCase();
  41. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : "";
  42. value = value.trim();
  43. if ( key === "newmtl" ) {
  44. // New material
  45. info = { name: value };
  46. materialsInfo[ value ] = info;
  47. } else if ( info ) {
  48. if ( key === "ka" || key === "kd" || key === "ks" ) {
  49. var ss = value.split( delimiter_pattern, 3 );
  50. info[ key ] = [ parseFloat( ss[0] ), parseFloat( ss[1] ), parseFloat( ss[2] ) ];
  51. } else {
  52. info[ key ] = value;
  53. }
  54. }
  55. }
  56. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.baseUrl, this.options );
  57. materialCreator.setMaterials( materialsInfo );
  58. return materialCreator;
  59. }
  60. };
  61. /**
  62. * Create a new THREE-MTLLoader.MaterialCreator
  63. * @param baseUrl - Url relative to which textures are loaded
  64. * @param options - Set of options on how to construct the materials
  65. * side: Which side to apply the material
  66. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  67. * wrap: What type of wrapping to apply for textures
  68. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  69. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  70. * Default: false, assumed to be already normalized
  71. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  72. * Default: false
  73. * invertTransparency: If transparency need to be inverted (inversion is needed if d = 0 is fully opaque)
  74. * Default: false (d = 1 is fully opaque)
  75. * @constructor
  76. */
  77. THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
  78. this.baseUrl = baseUrl;
  79. this.options = options;
  80. this.materialsInfo = {};
  81. this.materials = {};
  82. this.materialsArray = [];
  83. this.nameLookup = {};
  84. this.side = ( this.options && this.options.side )? this.options.side: THREE.FrontSide;
  85. this.wrap = ( this.options && this.options.wrap )? this.options.wrap: THREE.RepeatWrapping;
  86. };
  87. THREE.MTLLoader.MaterialCreator.prototype = {
  88. constructor: THREE.MTLLoader.MaterialCreator,
  89. setMaterials: function( materialsInfo ) {
  90. this.materialsInfo = this.convert( materialsInfo );
  91. this.materials = {};
  92. this.materialsArray = [];
  93. this.nameLookup = {};
  94. },
  95. convert: function( materialsInfo ) {
  96. if ( !this.options ) return materialsInfo;
  97. var converted = {};
  98. for ( var mn in materialsInfo ) {
  99. // Convert materials info into normalized form based on options
  100. var mat = materialsInfo[ mn ];
  101. var covmat = {};
  102. converted[ mn ] = covmat;
  103. for ( var prop in mat ) {
  104. var save = true;
  105. var value = mat[ prop ];
  106. var lprop = prop.toLowerCase();
  107. switch ( lprop ) {
  108. case 'kd':
  109. case 'ka':
  110. case 'ks':
  111. // Diffuse color (color under white light) using RGB values
  112. if ( this.options && this.options.normalizeRGB ) {
  113. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  114. }
  115. if ( this.options && this.options.ignoreZeroRGBs ) {
  116. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 1 ] === 0 ) {
  117. // ignore
  118. save = false;
  119. }
  120. }
  121. break;
  122. case 'd':
  123. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  124. // d is dissolve for current material
  125. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  126. if ( this.options && this.options.invertTransparency ) {
  127. value = 1 - value;
  128. }
  129. break;
  130. default:
  131. break;
  132. }
  133. if ( save ) {
  134. covmat[ lprop ] = value;
  135. }
  136. }
  137. }
  138. return converted;
  139. },
  140. preload: function () {
  141. for ( var mn in this.materialsInfo ) {
  142. this.create( mn );
  143. }
  144. },
  145. getIndex: function( materialName ) {
  146. return this.nameLookup[ materialName ];
  147. },
  148. getAsArray: function() {
  149. var index = 0;
  150. for ( var mn in this.materialsInfo ) {
  151. this.materialsArray[ index ] = this.create( mn );
  152. this.nameLookup[ mn ] = index;
  153. index ++;
  154. }
  155. return this.materialsArray;
  156. },
  157. create: function ( materialName ) {
  158. if ( this.materials[ materialName ] === undefined ) {
  159. this.createMaterial_( materialName );
  160. }
  161. return this.materials[ materialName ];
  162. },
  163. createMaterial_: function ( materialName ) {
  164. // Create material
  165. var mat = this.materialsInfo[ materialName ];
  166. var params = {
  167. name: materialName,
  168. side: this.side
  169. };
  170. for ( var prop in mat ) {
  171. var value = mat[ prop ];
  172. switch ( prop.toLowerCase() ) {
  173. // Ns is material specular exponent
  174. case 'kd':
  175. // Diffuse color (color under white light) using RGB values
  176. params[ 'diffuse' ] = new THREE.Color().fromArray( value );
  177. break;
  178. case 'ka':
  179. // Ambient color (color under shadow) using RGB values
  180. params[ 'ambient' ] = new THREE.Color().fromArray( value );
  181. break;
  182. case 'ks':
  183. // Specular color (color when light is reflected from shiny surface) using RGB values
  184. params[ 'specular' ] = new THREE.Color().fromArray( value );
  185. break;
  186. case 'map_kd':
  187. // Diffuse texture map
  188. params[ 'map' ] = this.loadTexture( this.baseUrl + value );
  189. params[ 'map' ].wrapS = this.wrap;
  190. params[ 'map' ].wrapT = this.wrap;
  191. break;
  192. case 'ns':
  193. // The specular exponent (defines the focus of the specular highlight)
  194. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  195. params['shininess'] = value;
  196. break;
  197. case 'd':
  198. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  199. // d is dissolve for current material
  200. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  201. if ( value < 1 ) {
  202. params['transparent'] = true;
  203. params['opacity'] = value;
  204. }
  205. break;
  206. default:
  207. break;
  208. }
  209. }
  210. if ( params[ 'diffuse' ] ) {
  211. if ( !params[ 'ambient' ]) params[ 'ambient' ] = params[ 'diffuse' ];
  212. params[ 'color' ] = params[ 'diffuse' ];
  213. }
  214. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  215. return this.materials[ materialName ];
  216. },
  217. loadTexture: function ( url, mapping, onLoad, onError ) {
  218. var texture;
  219. var loader = THREE.Loader.Handlers.get( url );
  220. if ( loader !== null ) {
  221. texture = loader.load( url, onLoad );
  222. } else {
  223. texture = new THREE.Texture();
  224. loader = new THREE.ImageLoader();
  225. loader.crossOrigin = this.crossOrigin;
  226. loader.load( url, function ( image ) {
  227. texture.image = THREE.MTLLoader.ensurePowerOfTwo_( image );
  228. texture.needsUpdate = true;
  229. if ( onLoad ) onLoad( texture );
  230. } );
  231. }
  232. texture.mapping = mapping;
  233. return texture;
  234. }
  235. };
  236. THREE.MTLLoader.ensurePowerOfTwo_ = function ( image ) {
  237. if ( ! THREE.Math.isPowerOfTwo( image.width ) || ! THREE.Math.isPowerOfTwo( image.height ) ) {
  238. var canvas = document.createElement( "canvas" );
  239. canvas.width = THREE.MTLLoader.nextHighestPowerOfTwo_( image.width );
  240. canvas.height = THREE.MTLLoader.nextHighestPowerOfTwo_( image.height );
  241. var ctx = canvas.getContext("2d");
  242. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  243. return canvas;
  244. }
  245. return image;
  246. };
  247. THREE.MTLLoader.nextHighestPowerOfTwo_ = function( x ) {
  248. --x;
  249. for ( var i = 1; i < 32; i <<= 1 ) {
  250. x = x | x >> i;
  251. }
  252. return x + 1;
  253. };
  254. THREE.EventDispatcher.prototype.apply( THREE.MTLLoader.prototype );