MTLLoader.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**
  2. * Loads a Wavefront .mtl file specifying materials
  3. *
  4. * @author angelxuanchang
  5. */
  6. THREE.MTLLoader = function( baseUrl, options ) {
  7. THREE.EventDispatcher.call( this );
  8. this.baseUrl = baseUrl;
  9. this.options = options;
  10. };
  11. THREE.MTLLoader.prototype = {
  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. /**
  86. * Create a new THREE-MTLLoader.MaterialCreator
  87. * @param baseUrl - Url relative to which textures are loaded
  88. * @param options - Set of options on how to construct the materials
  89. * side: Which side to apply the material
  90. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  91. * wrap: What type of wrapping to apply for textures
  92. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  93. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  94. * Default: false, assumed to be already normalized
  95. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  96. * Default: false
  97. * invertTransparency: If transparency need to be inverted (inversion is needed if d = 0 is fully opaque)
  98. * Default: false (d = 1 is fully opaque)
  99. * @constructor
  100. */
  101. THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
  102. THREE.EventDispatcher.call( this );
  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. setMaterials: function( materialsInfo ) {
  114. this.materialsInfo = this.convert( materialsInfo );
  115. this.materials = {};
  116. this.materialsArray = [];
  117. this.nameLookup = {};
  118. },
  119. convert: function( materialsInfo ) {
  120. if ( !this.options ) return materialsInfo;
  121. var converted = {};
  122. for ( var mn in materialsInfo ) {
  123. // Convert materials info into normalized form based on options
  124. var mat = materialsInfo[ mn ];
  125. var covmat = {};
  126. converted[ mn ] = covmat;
  127. for ( var prop in mat ) {
  128. var save = true;
  129. var value = mat[ prop ];
  130. var lprop = prop.toLowerCase();
  131. switch ( lprop ) {
  132. case 'kd':
  133. case 'ka':
  134. case 'ks':
  135. // Diffuse color (color under white light) using RGB values
  136. if ( this.options && this.options.normalizeRGB ) {
  137. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  138. }
  139. if ( this.options && this.options.ignoreZeroRGBs ) {
  140. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 1 ] === 0 ) {
  141. // ignore
  142. save = false;
  143. }
  144. }
  145. break;
  146. case 'd':
  147. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  148. // d is dissolve for current material
  149. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  150. if ( this.options && this.options.invertTransparency ) {
  151. value = 1 - value;
  152. }
  153. break;
  154. default:
  155. break;
  156. }
  157. if ( save ) {
  158. covmat[ lprop ] = value;
  159. }
  160. }
  161. }
  162. return converted;
  163. },
  164. preload: function () {
  165. for ( var mn in this.materialsInfo ) {
  166. this.create( mn );
  167. }
  168. },
  169. getIndex: function( materialName ) {
  170. return this.nameLookup[ materialName ];
  171. },
  172. getAsArray: function() {
  173. var index = 0;
  174. for ( var mn in this.materialsInfo ) {
  175. this.materialsArray[ index ] = this.create( mn );
  176. this.nameLookup[ mn ] = index;
  177. index ++;
  178. }
  179. return this.materialsArray;
  180. },
  181. create: function ( materialName ) {
  182. if ( this.materials[ materialName ] === undefined ) {
  183. this.createMaterial_( materialName );
  184. }
  185. return this.materials[ materialName ];
  186. },
  187. createMaterial_: function ( materialName ) {
  188. // Create material
  189. var mat = this.materialsInfo[ materialName ];
  190. var params = {
  191. name: materialName,
  192. side: this.side
  193. };
  194. for ( var prop in mat ) {
  195. var value = mat[ prop ];
  196. switch ( prop.toLowerCase() ) {
  197. // Ns is material specular exponent
  198. case 'kd':
  199. // Diffuse color (color under white light) using RGB values
  200. params[ 'diffuse' ] = new THREE.Color().setRGB( value[0], value[1], value[2] );
  201. break;
  202. case 'ka':
  203. // Ambient color (color under shadow) using RGB values
  204. params[ 'ambient' ] = new THREE.Color().setRGB( value[0], value[1], value[2] );
  205. break;
  206. case 'ks':
  207. // Specular color (color when light is reflected from shiny surface) using RGB values
  208. params[ 'specular' ] = new THREE.Color().setRGB( value[0], value[1], value[2] );
  209. break;
  210. case 'map_kd':
  211. // Diffuse texture map
  212. params[ 'map' ] = THREE.MTLLoader.loadTexture( this.baseUrl + value );
  213. params[ 'map' ].wrapS = this.wrap;
  214. params[ 'map' ].wrapT = this.wrap;
  215. break;
  216. case 'ns':
  217. // The specular exponent (defines the focus of the specular highlight)
  218. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  219. params['shininess'] = value;
  220. break;
  221. case 'd':
  222. // According to MTL format (http://paulbourke.net/dataformats/mtl/):
  223. // d is dissolve for current material
  224. // factor of 1.0 is fully opaque, a factor of 0 is fully dissolved (completely transparent)
  225. if ( value < 1 ) {
  226. params['transparent'] = true;
  227. params['opacity'] = value;
  228. }
  229. break;
  230. default:
  231. break;
  232. }
  233. }
  234. if ( params[ 'diffuse' ] ) {
  235. if ( !params[ 'ambient' ]) params[ 'ambient' ] = params[ 'diffuse' ];
  236. params[ 'color' ] = params[ 'diffuse' ];
  237. }
  238. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  239. return this.materials[ materialName ];
  240. }
  241. };
  242. THREE.MTLLoader.loadTexture = function ( url, mapping, onLoad, onError ) {
  243. var isCompressed = url.toLowerCase().endsWith( ".dds" );
  244. if ( isCompressed ) {
  245. var texture = THREE.ImageUtils.loadCompressedTexture( url, mapping, onLoad, onError );
  246. } else {
  247. var image = new Image();
  248. var texture = new THREE.Texture( image, mapping );
  249. var loader = new THREE.ImageLoader();
  250. loader.addEventListener( 'load', function ( event ) {
  251. texture.image = THREE.MTLLoader.ensurePowerOfTwo_( event.content );
  252. texture.needsUpdate = true;
  253. if ( onLoad ) onLoad( texture );
  254. } );
  255. loader.addEventListener( 'error', function ( event ) {
  256. if ( onError ) onError( event.message );
  257. } );
  258. loader.crossOrigin = this.crossOrigin;
  259. loader.load( url, image );
  260. }
  261. return texture;
  262. };
  263. THREE.MTLLoader.ensurePowerOfTwo_ = function ( image ) {
  264. if ( ! THREE.MTLLoader.isPowerOfTwo_( image.width ) || ! THREE.MTLLoader.isPowerOfTwo_( image.height ) ) {
  265. var canvas = document.createElement( "canvas" );
  266. canvas.width = THREE.MTLLoader.nextHighestPowerOfTwo_( image.width );
  267. canvas.height = THREE.MTLLoader.nextHighestPowerOfTwo_( image.height );
  268. var ctx = canvas.getContext("2d");
  269. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  270. return canvas;
  271. }
  272. return image;
  273. };
  274. THREE.MTLLoader.isPowerOfTwo_ = function ( x ) {
  275. return ( x & ( x - 1 ) ) === 0;
  276. };
  277. THREE.MTLLoader.nextHighestPowerOfTwo_ = function( x ) {
  278. --x;
  279. for ( var i = 1; i < 32; i <<= 1 ) {
  280. x = x | x >> i;
  281. }
  282. return x + 1;
  283. };