MTLLoader.js 10 KB

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