MTLLoader.js 9.9 KB

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