OBJLoader2.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.OBJLoader2 === undefined ) { THREE.OBJLoader2 = {} }
  7. /**
  8. * Use this class to load OBJ data from files or to parse OBJ data from an arraybuffer
  9. * @class
  10. *
  11. * @param {THREE.DefaultLoadingManager} [manager] The loadingManager for the loader to use. Default is {@link THREE.DefaultLoadingManager}
  12. */
  13. THREE.OBJLoader2 = (function () {
  14. var OBJLOADER2_VERSION = '2.0.0-dev';
  15. var Validator = THREE.LoaderSupport.Validator;
  16. var Commons = THREE.LoaderSupport.Commons;
  17. OBJLoader2.prototype = Object.create( THREE.LoaderSupport.Commons.prototype );
  18. OBJLoader2.prototype.constructor = OBJLoader2;
  19. function OBJLoader2( manager ) {
  20. THREE.LoaderSupport.Commons.call( this, manager );
  21. console.log( "Using THREE.OBJLoader2 version: " + OBJLOADER2_VERSION );
  22. this.materialPerSmoothingGroup = false;
  23. this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
  24. this.workerSupport = null;
  25. this.terminateWorkerOnLoad = true;
  26. };
  27. /**
  28. * Tells whether a material shall be created per smoothing group
  29. * @memberOf THREE.OBJLoader2
  30. *
  31. * @param {boolean} materialPerSmoothingGroup=false Default is false
  32. */
  33. OBJLoader2.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  34. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  35. };
  36. /**
  37. * Sets debug mode for the parser
  38. * @memberOf THREE.OBJLoader2
  39. *
  40. * @param {boolean} enabled
  41. */
  42. OBJLoader2.prototype.setDebug = function ( enabled ) {
  43. THREE.LoaderSupport.Commons.prototype.setDebug.call( this, enabled );
  44. };
  45. /**
  46. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer
  47. * @memberOf THREE.OBJLoader2
  48. *
  49. * @param {string} url URL of the file to load
  50. * @param {callback} onLoad Called after loading was successfully completed
  51. * @param {callback} onProgress Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains {integer total} and {integer loaded} bytes.
  52. * @param {callback} onError Called after an error occurred during loading
  53. * @param {callback} onMeshAlter Called after a new mesh raw data becomes available
  54. * @param {boolean} useAsync Set this to use async loading
  55. */
  56. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, onMeshAlter, useAsync ) {
  57. var scope = this;
  58. if ( ! Validator.isValid( onProgress ) ) {
  59. var refPercentComplete = 0;
  60. var percentComplete = 0;
  61. onProgress = function ( event ) {
  62. if ( ! event.lengthComputable ) return;
  63. percentComplete = Math.round( event.loaded / event.total * 100 );
  64. if ( percentComplete > refPercentComplete ) {
  65. refPercentComplete = percentComplete;
  66. var output = 'Download of "' + url + '": ' + percentComplete + '%';
  67. console.log( output );
  68. scope.onProgress( output );
  69. }
  70. };
  71. }
  72. if ( ! Validator.isValid( onError ) ) {
  73. onError = function ( event ) {
  74. var output = 'Error occurred while downloading "' + url + '"';
  75. console.error( output + ': ' + event );
  76. scope.onProgress( output );
  77. };
  78. }
  79. this.fileLoader.setPath( this.path );
  80. this.fileLoader.setResponseType( 'arraybuffer' );
  81. this.fileLoader.load( url, function ( content ) {
  82. if ( useAsync ) {
  83. scope.parseAsync( content, onLoad );
  84. } else {
  85. scope._setCallbacks( null, onMeshAlter, null );
  86. onLoad( scope.parse( content ), scope.modelName, scope.instanceNo );
  87. }
  88. }, onProgress, onError );
  89. };
  90. /**
  91. * Run the loader according the provided instructions.
  92. * @memberOf THREE.OBJLoader2
  93. *
  94. * @param {THREE.LoaderSupport.PrepData} prepData All parameters and resources required for execution
  95. * @param {THREE.LoaderSupport.WorkerSupport} [workerSupportExternal] Use pre-existing WorkerSupport
  96. */
  97. OBJLoader2.prototype.run = function ( prepData, workerSupportExternal ) {
  98. this._applyPrepData( prepData );
  99. var available = this._checkFiles( prepData.resources );
  100. if ( Validator.isValid( workerSupportExternal ) ) {
  101. this.terminateWorkerOnLoad = false;
  102. this.workerSupport = workerSupportExternal;
  103. } else {
  104. this.terminateWorkerOnLoad = true;
  105. }
  106. var scope = this;
  107. var onMaterialsLoaded = function ( materials ) {
  108. scope.builder.setMaterials( materials );
  109. if ( Validator.isValid( available.obj.content ) ) {
  110. if ( prepData.useAsync ) {
  111. scope.parseAsync( available.obj.content, scope.callbacks.onLoad );
  112. } else {
  113. scope.parse( available.obj.content );
  114. }
  115. } else {
  116. scope.setPath( available.obj.path );
  117. scope.load( available.obj.name, scope.callbacks.onLoad, null, null, scope.callbacks.onMeshAlter, prepData.useAsync );
  118. }
  119. };
  120. this._loadMtl( available.mtl, onMaterialsLoaded, prepData.crossOrigin );
  121. };
  122. OBJLoader2.prototype._applyPrepData = function ( prepData ) {
  123. THREE.LoaderSupport.Commons.prototype._applyPrepData.call( this, prepData );
  124. if ( Validator.isValid( prepData ) ) {
  125. this.setMaterialPerSmoothingGroup( prepData.materialPerSmoothingGroup );
  126. }
  127. };
  128. /**
  129. * Parses OBJ content synchronously.
  130. * @memberOf THREE.OBJLoader2
  131. *
  132. * @param content
  133. */
  134. OBJLoader2.prototype.parse = function ( content ) {
  135. console.time( 'OBJLoader2 parse: ' + this.modelName );
  136. var parser = new Parser();
  137. parser.setMaterialPerSmoothingGroup( this.materialPerSmoothingGroup );
  138. parser.setUseIndices( this.useIndices );
  139. parser.setDisregardNormals( this.disregardNormals );
  140. parser.setMaterialNames( this.builder.materialNames );
  141. parser.setDebug( this.debug );
  142. var scope = this;
  143. var onMeshLoaded = function ( payload ) {
  144. var meshes = scope.builder.buildMeshes( payload );
  145. var mesh;
  146. for ( var i in meshes ) {
  147. mesh = meshes[ i ];
  148. scope.loaderRootNode.add( mesh );
  149. }
  150. };
  151. parser.setCallbackBuilder( onMeshLoaded );
  152. var onProgressScoped = function ( message ) {
  153. scope.onProgress( message );
  154. };
  155. parser.setCallbackProgress( onProgressScoped );
  156. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  157. console.log( 'Parsing arrayBuffer...' );
  158. parser.parse( content );
  159. } else if ( typeof( content ) === 'string' || content instanceof String ) {
  160. console.log( 'Parsing text...' );
  161. parser.parseText( content );
  162. } else {
  163. throw 'Provided content was neither of type String nor Uint8Array! Aborting...';
  164. }
  165. console.timeEnd( 'OBJLoader2 parse: ' + this.modelName );
  166. return this.loaderRootNode;
  167. };
  168. /**
  169. * Parses OBJ content asynchronously.
  170. * @memberOf THREE.OBJLoader2
  171. *
  172. * @param {arraybuffer} content
  173. * @param {callback} onLoad
  174. */
  175. OBJLoader2.prototype.parseAsync = function ( content, onLoad ) {
  176. console.time( 'OBJLoader2 parseAsync: ' + this.modelName);
  177. var scope = this;
  178. var scopedOnLoad = function ( message ) {
  179. onLoad( scope.loaderRootNode, scope.modelName, scope.instanceNo, message );
  180. if ( scope.terminateWorkerOnLoad ) scope.workerSupport.terminateWorker();
  181. console.timeEnd( 'OBJLoader2 parseAsync: ' + scope.modelName );
  182. };
  183. var scopedOnMeshLoaded = function ( payload ) {
  184. var meshes = scope.builder.buildMeshes( payload );
  185. var mesh;
  186. for ( var i in meshes ) {
  187. mesh = meshes[ i ];
  188. scope.loaderRootNode.add( mesh );
  189. }
  190. };
  191. this.workerSupport = Validator.verifyInput( this.workerSupport, new THREE.LoaderSupport.WorkerSupport() );
  192. var buildCode = function ( funcBuildObject, funcBuildSingelton ) {
  193. var workerCode = '';
  194. workerCode += '/**\n';
  195. workerCode += ' * This code was constructed by OBJLoader2 buildWorkerCode.\n';
  196. workerCode += ' */\n\n';
  197. workerCode += funcBuildSingelton( 'Commons', 'Commons', Commons );
  198. workerCode += funcBuildObject( 'Consts', Consts );
  199. workerCode += funcBuildObject( 'Validator', Validator );
  200. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  201. workerCode += funcBuildSingelton( 'RawMesh', 'RawMesh', RawMesh );
  202. workerCode += funcBuildSingelton( 'RawMeshSubGroup', 'RawMeshSubGroup', RawMeshSubGroup );
  203. return workerCode;
  204. };
  205. this.workerSupport.validate( buildCode, false );
  206. this.workerSupport.setCallbacks( scopedOnMeshLoaded, scopedOnLoad );
  207. this.workerSupport.run(
  208. {
  209. cmd: 'run',
  210. params: {
  211. debug: this.debug,
  212. materialPerSmoothingGroup: this.materialPerSmoothingGroup,
  213. useIndices: this.useIndices,
  214. disregardNormals: this.disregardNormals
  215. },
  216. materials: {
  217. materialNames: this.builder.materialNames
  218. },
  219. buffers: {
  220. input: content
  221. }
  222. },
  223. [ content.buffer ]
  224. );
  225. };
  226. /**
  227. * Constants used by THREE.OBJLoader2
  228. */
  229. var Consts = {
  230. CODE_LF: 10,
  231. CODE_CR: 13,
  232. CODE_SPACE: 32,
  233. CODE_SLASH: 47,
  234. STRING_LF: '\n',
  235. STRING_CR: '\r',
  236. STRING_SPACE: ' ',
  237. STRING_SLASH: '/',
  238. LINE_F: 'f',
  239. LINE_G: 'g',
  240. LINE_L: 'l',
  241. LINE_O: 'o',
  242. LINE_S: 's',
  243. LINE_V: 'v',
  244. LINE_VT: 'vt',
  245. LINE_VN: 'vn',
  246. LINE_MTLLIB: 'mtllib',
  247. LINE_USEMTL: 'usemtl'
  248. };
  249. /**
  250. * Parse OBJ data either from ArrayBuffer or string
  251. * @class
  252. */
  253. var Parser = (function () {
  254. function Parser() {
  255. this.callbackProgress = null;
  256. this.callbackBuilder = null;
  257. this.materialNames = [];
  258. this.debug = false;
  259. this.rawMesh = null;
  260. this.materialPerSmoothingGroup = false;
  261. this.useIndices = false;
  262. this.disregardNormals = false;
  263. this.inputObjectCount = 1;
  264. this.outputObjectCount = 1;
  265. this.counts = {
  266. vertices: 0,
  267. faces: 0,
  268. doubleIndicesCount: 0
  269. };
  270. };
  271. Parser.prototype.setDebug = function ( debug ) {
  272. if ( debug === true || debug === false ) this.debug = debug;
  273. };
  274. Parser.prototype.configure = function () {
  275. this.rawMesh = new RawMesh( this.materialPerSmoothingGroup, this.useIndices, this.disregardNormals );
  276. var matNames = ( this.materialNames.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + this.materialNames.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  277. var printConfig = 'OBJLoader2.Parser configuration:'
  278. + '\n\tdebug: ' + this.debug
  279. + matNames
  280. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  281. + '\n\tuseIndices: ' + this.useIndices
  282. + '\n\tdisregardNormals: ' +this.disregardNormals;
  283. console.log( printConfig );
  284. };
  285. Parser.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  286. this.materialPerSmoothingGroup = materialPerSmoothingGroup;
  287. };
  288. Parser.prototype.setUseIndices = function ( useIndices ) {
  289. this.useIndices = useIndices;
  290. };
  291. Parser.prototype.setDisregardNormals = function ( disregardNormals ) {
  292. this.disregardNormals = disregardNormals;
  293. };
  294. Parser.prototype.setMaterialNames = function ( materialNames ) {
  295. this.materialNames = Validator.verifyInput( materialNames, this.materialNames );
  296. this.materialNames = Validator.verifyInput( this.materialNames, [] );
  297. };
  298. Parser.prototype.setCallbackBuilder = function ( callbackBuilder ) {
  299. this.callbackBuilder = callbackBuilder;
  300. if ( ! Validator.isValid( this.callbackBuilder ) ) throw 'Unable to run as no "builder" callback is set.';
  301. };
  302. Parser.prototype.setCallbackProgress = function ( callbackProgress ) {
  303. this.callbackProgress = callbackProgress;
  304. };
  305. /**
  306. * Parse the provided arraybuffer
  307. * @memberOf Parser
  308. *
  309. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  310. */
  311. Parser.prototype.parse = function ( arrayBuffer ) {
  312. console.time( 'OBJLoader2.Parser.parse' );
  313. this.configure();
  314. var arrayBufferView = new Uint8Array( arrayBuffer );
  315. var length = arrayBufferView.byteLength;
  316. var buffer = new Array( 128 );
  317. var bufferPointer = 0;
  318. var slashesCount = 0;
  319. var reachedFaces = false;
  320. var code;
  321. var word = '';
  322. for ( var i = 0; i < length; i++ ) {
  323. code = arrayBufferView[ i ];
  324. switch ( code ) {
  325. case Consts.CODE_SPACE:
  326. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  327. word = '';
  328. break;
  329. case Consts.CODE_SLASH:
  330. slashesCount++;
  331. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  332. word = '';
  333. break;
  334. case Consts.CODE_LF:
  335. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  336. word = '';
  337. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  338. bufferPointer = 0;
  339. slashesCount = 0;
  340. break;
  341. case Consts.CODE_CR:
  342. break;
  343. default:
  344. word += String.fromCharCode( code );
  345. break;
  346. }
  347. }
  348. this.finalize();
  349. console.timeEnd( 'OBJLoader2.Parser.parse' );
  350. };
  351. /**
  352. * Parse the provided text
  353. * @memberOf Parser
  354. *
  355. * @param {string} text OBJ data as string
  356. */
  357. Parser.prototype.parseText = function ( text ) {
  358. console.time( 'OBJLoader2.Parser.parseText' );
  359. this.configure();
  360. var length = text.length;
  361. var buffer = new Array( 128 );
  362. var bufferPointer = 0;
  363. var slashesCount = 0;
  364. var reachedFaces = false;
  365. var char;
  366. var word = '';
  367. for ( var i = 0; i < length; i++ ) {
  368. char = text[ i ];
  369. switch ( char ) {
  370. case Consts.STRING_SPACE:
  371. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  372. word = '';
  373. break;
  374. case Consts.STRING_SLASH:
  375. slashesCount++;
  376. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  377. word = '';
  378. break;
  379. case Consts.STRING_LF:
  380. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  381. word = '';
  382. reachedFaces = this.processLine( buffer, bufferPointer, slashesCount, reachedFaces );
  383. bufferPointer = 0;
  384. slashesCount = 0;
  385. break;
  386. case Consts.STRING_CR:
  387. break;
  388. default:
  389. word += char;
  390. }
  391. }
  392. this.finalize();
  393. console.timeEnd( 'OBJLoader2.Parser.parseText' );
  394. };
  395. Parser.prototype.processLine = function ( buffer, bufferPointer, slashesCount, reachedFaces ) {
  396. if ( bufferPointer < 1 ) return reachedFaces;
  397. var bufferLength = bufferPointer - 1;
  398. var concatBuffer;
  399. switch ( buffer[ 0 ] ) {
  400. case Consts.LINE_V:
  401. // object complete instance required if reached faces already (= reached next block of v)
  402. if ( reachedFaces ) {
  403. if ( this.rawMesh.colors.length > 0 && this.rawMesh.colors.length !== this.rawMesh.vertices.length ) {
  404. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  405. }
  406. this.processCompletedObject( null, this.rawMesh.groupName );
  407. reachedFaces = false;
  408. }
  409. if ( bufferLength === 3 ) {
  410. this.rawMesh.pushVertex( buffer )
  411. } else {
  412. this.rawMesh.pushVertexAndVertextColors( buffer );
  413. }
  414. break;
  415. case Consts.LINE_VT:
  416. this.rawMesh.pushUv( buffer );
  417. break;
  418. case Consts.LINE_VN:
  419. this.rawMesh.pushNormal( buffer );
  420. break;
  421. case Consts.LINE_F:
  422. reachedFaces = true;
  423. this.rawMesh.processFaces( buffer, bufferPointer, slashesCount );
  424. break;
  425. case Consts.LINE_L:
  426. if ( bufferLength === slashesCount * 2 ) {
  427. this.rawMesh.buildLineVvt( buffer );
  428. } else {
  429. this.rawMesh.buildLineV( buffer );
  430. }
  431. break;
  432. case Consts.LINE_S:
  433. this.rawMesh.pushSmoothingGroup( buffer[ 1 ] );
  434. this.flushStringBuffer( buffer, bufferPointer );
  435. break;
  436. case Consts.LINE_G:
  437. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  438. this.processCompletedGroup( concatBuffer );
  439. this.flushStringBuffer( buffer, bufferPointer );
  440. break;
  441. case Consts.LINE_O:
  442. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  443. if ( this.rawMesh.vertices.length > 0 ) {
  444. this.processCompletedObject( concatBuffer, null );
  445. reachedFaces = false;
  446. } else {
  447. this.rawMesh.pushObject( concatBuffer );
  448. }
  449. this.flushStringBuffer( buffer, bufferPointer );
  450. break;
  451. case Consts.LINE_MTLLIB:
  452. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  453. this.rawMesh.pushMtllib( concatBuffer );
  454. this.flushStringBuffer( buffer, bufferPointer );
  455. break;
  456. case Consts.LINE_USEMTL:
  457. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  458. this.rawMesh.pushUsemtl( concatBuffer );
  459. this.flushStringBuffer( buffer, bufferPointer );
  460. break;
  461. default:
  462. break;
  463. }
  464. return reachedFaces;
  465. };
  466. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  467. for ( var i = 0; i < bufferLength; i++ ) {
  468. buffer[ i ] = '';
  469. }
  470. };
  471. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  472. var result = this.rawMesh.finalize( this.debug );
  473. if ( Validator.isValid( result ) ) {
  474. this.inputObjectCount++;
  475. if ( this.debug ) this.rawMesh.createReport( this.inputObjectCount, true );
  476. var message = this.buildMesh( result, this.inputObjectCount );
  477. this.onProgress( message );
  478. }
  479. this.rawMesh = this.rawMesh.newInstanceFromObject( objectName, groupName );
  480. };
  481. Parser.prototype.processCompletedGroup = function ( groupName ) {
  482. var result = this.rawMesh.finalize();
  483. if ( Validator.isValid( result ) ) {
  484. this.inputObjectCount++;
  485. if ( this.debug ) this.rawMesh.createReport( this.inputObjectCount, true );
  486. var message = this.buildMesh( result, this.inputObjectCount );
  487. this.onProgress( message );
  488. this.rawMesh = this.rawMesh.newInstanceFromGroup( groupName );
  489. } else {
  490. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  491. this.rawMesh.pushGroup( groupName );
  492. }
  493. };
  494. Parser.prototype.finalize = function () {
  495. console.log( 'Global output object count: ' + this.outputObjectCount );
  496. var result = Validator.isValid( this.rawMesh ) ? this.rawMesh.finalize() : null;
  497. if ( Validator.isValid( result ) ) {
  498. this.inputObjectCount++;
  499. if ( this.debug ) this.rawMesh.createReport( this.inputObjectCount, true );
  500. var message = this.buildMesh( result, this.inputObjectCount );
  501. console.log(
  502. 'Overall counts: ' +
  503. '\n\tVertices: ' + this.counts.vertices,
  504. '\n\tFaces: ' + this.counts.faces,
  505. '\n\tMultiple definitions: ' + this.counts.doubleIndicesCount
  506. );
  507. this.onProgress( message );
  508. }
  509. };
  510. Parser.prototype.onProgress = function ( text ) {
  511. if ( Validator.isValid( text ) && Validator.isValid( this.callbackProgress) ) this.callbackProgress( text );
  512. };
  513. /**
  514. * RawObjectDescriptions are transformed to too intermediate format that is forwarded to the Builder.
  515. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  516. *
  517. * @param result
  518. */
  519. Parser.prototype.buildMesh = function ( result ) {
  520. var rawObjectDescriptions = result.subGroups;
  521. var vertexFA = new Float32Array( result.absoluteVertexCount );
  522. this.counts.vertices += result.absoluteVertexCount / 3;
  523. this.counts.faces += result.faceCount;
  524. this.counts.doubleIndicesCount += result.doubleIndicesCount;
  525. var indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  526. var colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  527. var normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  528. var uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  529. var rawObjectDescription;
  530. var materialDescription;
  531. var materialDescriptions = [];
  532. var createMultiMaterial = ( rawObjectDescriptions.length > 1 );
  533. var materialIndex = 0;
  534. var materialIndexMapping = [];
  535. var selectedMaterialIndex;
  536. var materialGroup;
  537. var materialGroups = [];
  538. var vertexFAOffset = 0;
  539. var indexUAOffset = 0;
  540. var colorFAOffset = 0;
  541. var normalFAOffset = 0;
  542. var uvFAOffset = 0;
  543. var materialGroupOffset = 0;
  544. var materialGroupLength = 0;
  545. for ( var oodIndex in rawObjectDescriptions ) {
  546. if ( ! rawObjectDescriptions.hasOwnProperty( oodIndex ) ) continue;
  547. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  548. materialDescription = {
  549. name: rawObjectDescription.materialName,
  550. flat: false,
  551. default: false
  552. };
  553. if ( this.materialNames[ materialDescription.name ] === null ) {
  554. materialDescription.default = true;
  555. console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName + '" was defined without material! Assigning "defaultMaterial".' );
  556. }
  557. // Attach '_flat' to materialName in case flat shading is needed due to smoothingGroup 0
  558. if ( rawObjectDescription.smoothingGroup === 0 ) materialDescription.flat = true;
  559. if ( createMultiMaterial ) {
  560. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  561. selectedMaterialIndex = materialIndexMapping[ materialDescription.name ];
  562. if ( ! selectedMaterialIndex ) {
  563. selectedMaterialIndex = materialIndex;
  564. materialIndexMapping[ materialDescription.name ] = materialIndex;
  565. materialDescriptions.push( materialDescription );
  566. materialIndex++;
  567. }
  568. materialGroupLength = this.useIndices ? rawObjectDescription.indices.length : rawObjectDescription.vertices.length / 3;
  569. materialGroup = {
  570. start: materialGroupOffset,
  571. count: materialGroupLength,
  572. index: selectedMaterialIndex
  573. };
  574. materialGroups.push( materialGroup );
  575. materialGroupOffset += materialGroupLength;
  576. } else {
  577. materialDescriptions.push( materialDescription );
  578. }
  579. vertexFA.set( rawObjectDescription.vertices, vertexFAOffset );
  580. vertexFAOffset += rawObjectDescription.vertices.length;
  581. if ( indexUA ) {
  582. indexUA.set( rawObjectDescription.indices, indexUAOffset );
  583. indexUAOffset += rawObjectDescription.indices.length;
  584. }
  585. if ( colorFA ) {
  586. colorFA.set( rawObjectDescription.colors, colorFAOffset );
  587. colorFAOffset += rawObjectDescription.colors.length;
  588. }
  589. if ( normalFA ) {
  590. normalFA.set( rawObjectDescription.normals, normalFAOffset );
  591. normalFAOffset += rawObjectDescription.normals.length;
  592. }
  593. if ( uvFA ) {
  594. uvFA.set( rawObjectDescription.uvs, uvFAOffset );
  595. uvFAOffset += rawObjectDescription.uvs.length;
  596. }
  597. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  598. }
  599. this.outputObjectCount++;
  600. this.callbackBuilder(
  601. {
  602. cmd: 'meshData',
  603. params: {
  604. meshName: result.name
  605. },
  606. materials: {
  607. multiMaterial: createMultiMaterial,
  608. materialDescriptions: materialDescriptions,
  609. materialGroups: materialGroups
  610. },
  611. buffers: {
  612. vertices: vertexFA,
  613. indices: indexUA,
  614. colors: colorFA,
  615. normals: normalFA,
  616. uvs: uvFA
  617. }
  618. },
  619. [ vertexFA.buffer ],
  620. Validator.isValid( indexUA ) ? [ indexUA.buffer ] : null,
  621. Validator.isValid( colorFA ) ? [ colorFA.buffer ] : null,
  622. Validator.isValid( normalFA ) ? [ normalFA.buffer ] : null,
  623. Validator.isValid( uvFA ) ? [ uvFA.buffer ] : null
  624. );
  625. };
  626. Parser.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  627. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n\tmaterialIndex: ' + selectedMaterialIndex : '';
  628. console.log(
  629. '\tOutput Object no.: ' + this.outputObjectCount +
  630. '\n\tobjectName: ' + rawObjectDescription.objectName +
  631. '\n\tgroupName: ' + rawObjectDescription.groupName +
  632. '\n\tmaterialName: ' + rawObjectDescription.materialName +
  633. materialIndexLine +
  634. '\n\tsmoothingGroup: ' + rawObjectDescription.smoothingGroup +
  635. '\n\t#vertices: ' + rawObjectDescription.vertices.length / 3 +
  636. '\n\t#indices: ' + rawObjectDescription.indices.length +
  637. '\n\t#colors: ' + rawObjectDescription.colors.length / 3 +
  638. '\n\t#uvs: ' + rawObjectDescription.uvs.length / 2 +
  639. '\n\t#normals: ' + rawObjectDescription.normals.length / 3
  640. );
  641. };
  642. return Parser;
  643. })();
  644. /**
  645. * {@link RawMesh} is only used by {@link Parser}.
  646. * The user of OBJLoader2 does not need to care about this class.
  647. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  648. */
  649. var RawMesh = (function () {
  650. function RawMesh( materialPerSmoothingGroup, useIndices, disregardNormals, objectName, groupName, activeMtlName ) {
  651. this.globalVertexOffset = 1;
  652. this.globalUvOffset = 1;
  653. this.globalNormalOffset = 1;
  654. this.vertices = [];
  655. this.colors = [];
  656. this.normals = [];
  657. this.uvs = [];
  658. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  659. this.activeMtlName = Validator.verifyInput( activeMtlName, '' );
  660. this.objectName = Validator.verifyInput( objectName, '' );
  661. this.groupName = Validator.verifyInput( groupName, '' );
  662. this.mtllibName = '';
  663. this.smoothingGroup = {
  664. splitMaterials: materialPerSmoothingGroup === true,
  665. normalized: -1,
  666. real: -1
  667. };
  668. this.useIndices = useIndices === true;
  669. this.disregardNormals = disregardNormals === true;
  670. this.mtlCount = 0;
  671. this.smoothingGroupCount = 0;
  672. this.subGroups = [];
  673. this.subGroupInUse = null;
  674. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  675. this.pushSmoothingGroup( 1 );
  676. this.doubleIndicesCount = 0;
  677. this.faceCount = 0;
  678. }
  679. RawMesh.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  680. var newRawObject = new RawMesh( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, objectName, groupName, this.activeMtlName );
  681. // move indices forward
  682. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  683. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  684. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  685. return newRawObject;
  686. };
  687. RawMesh.prototype.newInstanceFromGroup = function ( groupName ) {
  688. var newRawObject = new RawMesh( this.smoothingGroup.splitMaterials, this.useIndices, this.disregardNormals, this.objectName, groupName, this.activeMtlName );
  689. // keep current buffers and indices forward
  690. newRawObject.vertices = this.vertices;
  691. newRawObject.colors = this.colors;
  692. newRawObject.uvs = this.uvs;
  693. newRawObject.normals = this.normals;
  694. newRawObject.globalVertexOffset = this.globalVertexOffset;
  695. newRawObject.globalUvOffset = this.globalUvOffset;
  696. newRawObject.globalNormalOffset = this.globalNormalOffset;
  697. return newRawObject;
  698. };
  699. RawMesh.prototype.pushVertex = function ( buffer ) {
  700. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  701. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  702. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  703. };
  704. RawMesh.prototype.pushVertexAndVertextColors = function ( buffer ) {
  705. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  706. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  707. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  708. this.colors.push( parseFloat( buffer[ 4 ] ) );
  709. this.colors.push( parseFloat( buffer[ 5 ] ) );
  710. this.colors.push( parseFloat( buffer[ 6 ] ) );
  711. };
  712. RawMesh.prototype.pushUv = function ( buffer ) {
  713. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  714. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  715. };
  716. RawMesh.prototype.pushNormal = function ( buffer ) {
  717. this.normals.push( parseFloat( buffer[ 1 ] ) );
  718. this.normals.push( parseFloat( buffer[ 2 ] ) );
  719. this.normals.push( parseFloat( buffer[ 3 ] ) );
  720. };
  721. RawMesh.prototype.pushObject = function ( objectName ) {
  722. this.objectName = Validator.verifyInput( objectName, '' );
  723. };
  724. RawMesh.prototype.pushMtllib = function ( mtllibName ) {
  725. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  726. };
  727. RawMesh.prototype.pushGroup = function ( groupName ) {
  728. this.groupName = Validator.verifyInput( groupName, '' );
  729. };
  730. RawMesh.prototype.pushUsemtl = function ( mtlName ) {
  731. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  732. this.activeMtlName = mtlName;
  733. this.mtlCount++;
  734. this.verifyIndex();
  735. };
  736. RawMesh.prototype.pushSmoothingGroup = function ( smoothingGroup ) {
  737. var smoothingGroupInt = parseInt( smoothingGroup );
  738. if ( isNaN( smoothingGroupInt ) ) {
  739. smoothingGroupInt = smoothingGroup === "off" ? 0 : 1;
  740. }
  741. var smoothCheck = this.smoothingGroup.normalized;
  742. this.smoothingGroup.normalized = this.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  743. this.smoothingGroup.real = smoothingGroupInt;
  744. if ( smoothCheck !== smoothingGroupInt ) {
  745. this.smoothingGroupCount++;
  746. this.verifyIndex();
  747. }
  748. };
  749. RawMesh.prototype.verifyIndex = function () {
  750. var index = this.activeMtlName + '|' + this.smoothingGroup.normalized;
  751. this.subGroupInUse = this.subGroups[ index ];
  752. if ( ! Validator.isValid( this.subGroupInUse ) ) {
  753. this.subGroupInUse = new RawMeshSubGroup( this.objectName, this.groupName, this.activeMtlName, this.smoothingGroup.normalized );
  754. this.subGroups[ index ] = this.subGroupInUse;
  755. }
  756. };
  757. RawMesh.prototype.processFaces = function ( buffer, bufferPointer, slashesCount ) {
  758. var bufferLength = bufferPointer - 1;
  759. var i, length;
  760. // "f vertex ..."
  761. if ( slashesCount === 0 ) {
  762. for ( i = 2, length = bufferLength - 1; i < length; i ++ ) {
  763. this.buildFace( buffer[ 1 ] );
  764. this.buildFace( buffer[ i ] );
  765. this.buildFace( buffer[ i + 1 ] );
  766. }
  767. // "f vertex/uv ..."
  768. } else if ( bufferLength === slashesCount * 2 ) {
  769. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  770. this.buildFace( buffer[ 1 ], buffer[ 2 ] );
  771. this.buildFace( buffer[ i ], buffer[ i + 1 ] );
  772. this.buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  773. }
  774. // "f vertex/uv/normal ..."
  775. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  776. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  777. this.buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  778. this.buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  779. this.buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  780. }
  781. // "f vertex//normal ..."
  782. } else {
  783. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  784. this.buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  785. this.buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  786. this.buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  787. }
  788. }
  789. };
  790. RawMesh.prototype.buildFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  791. var sgiu = this.subGroupInUse;
  792. if ( this.disregardNormals ) faceIndexN = undefined;
  793. var scope = this;
  794. var updateRawObjectDescriptionInUse = function () {
  795. var indexPointerV = ( parseInt( faceIndexV ) - scope.globalVertexOffset ) * 3;
  796. var indexPointerC = scope.colors.length > 0 ? indexPointerV : null;
  797. var vertices = sgiu.vertices;
  798. vertices.push( scope.vertices[ indexPointerV++ ] );
  799. vertices.push( scope.vertices[ indexPointerV++ ] );
  800. vertices.push( scope.vertices[ indexPointerV ] );
  801. if ( indexPointerC !== null ) {
  802. var colors = sgiu.colors;
  803. colors.push( scope.colors[ indexPointerC++ ] );
  804. colors.push( scope.colors[ indexPointerC++ ] );
  805. colors.push( scope.colors[ indexPointerC ] );
  806. }
  807. if ( faceIndexU ) {
  808. var indexPointerU = ( parseInt( faceIndexU ) - scope.globalUvOffset ) * 2;
  809. var uvs = sgiu.uvs;
  810. uvs.push( scope.uvs[ indexPointerU++ ] );
  811. uvs.push( scope.uvs[ indexPointerU ] );
  812. }
  813. if ( faceIndexN ) {
  814. var indexPointerN = ( parseInt( faceIndexN ) - scope.globalNormalOffset ) * 3;
  815. var normals = sgiu.normals;
  816. normals.push( scope.normals[ indexPointerN++ ] );
  817. normals.push( scope.normals[ indexPointerN++ ] );
  818. normals.push( scope.normals[ indexPointerN ] );
  819. }
  820. };
  821. if ( this.useIndices ) {
  822. var mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  823. var indicesPointer = sgiu.indexMappings[ mappingName ];
  824. if ( Validator.isValid( indicesPointer ) ) {
  825. this.doubleIndicesCount++;
  826. } else {
  827. indicesPointer = sgiu.vertices.length / 3;
  828. updateRawObjectDescriptionInUse();
  829. sgiu.indexMappings[ mappingName ] = indicesPointer;
  830. sgiu.indexMappingsCount++;
  831. }
  832. sgiu.indices.push( indicesPointer );
  833. } else {
  834. updateRawObjectDescriptionInUse();
  835. }
  836. this.faceCount++;
  837. };
  838. /*
  839. * Support for lines with or without texture. First element in indexArray is the line identification
  840. * 0: "f vertex/uv vertex/uv ..."
  841. * 1: "f vertex vertex ..."
  842. */
  843. RawMesh.prototype.buildLineVvt = function ( lineArray ) {
  844. for ( var i = 1, length = lineArray.length; i < length; i ++ ) {
  845. this.vertices.push( parseInt( lineArray[ i ] ) );
  846. this.uvs.push( parseInt( lineArray[ i ] ) );
  847. }
  848. };
  849. RawMesh.prototype.buildLineV = function ( lineArray ) {
  850. for ( var i = 1, length = lineArray.length; i < length; i++ ) {
  851. this.vertices.push( parseInt( lineArray[ i ] ) );
  852. }
  853. };
  854. /**
  855. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  856. */
  857. RawMesh.prototype.finalize = function () {
  858. var rawObjectDescriptionsTemp = [];
  859. var rawObjectDescription;
  860. var absoluteVertexCount = 0;
  861. var absoluteIndexMappingsCount = 0;
  862. var absoluteIndexCount = 0;
  863. var absoluteColorCount = 0;
  864. var absoluteNormalCount = 0;
  865. var absoluteUvCount = 0;
  866. var indices;
  867. for ( var name in this.subGroups ) {
  868. rawObjectDescription = this.subGroups[ name ];
  869. if ( rawObjectDescription.vertices.length > 0 ) {
  870. indices = rawObjectDescription.indices;
  871. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  872. for ( var i in indices ) indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  873. }
  874. rawObjectDescriptionsTemp.push( rawObjectDescription );
  875. absoluteVertexCount += rawObjectDescription.vertices.length;
  876. absoluteIndexMappingsCount += rawObjectDescription.indexMappingsCount;
  877. absoluteIndexCount += rawObjectDescription.indices.length;
  878. absoluteColorCount += rawObjectDescription.colors.length;
  879. absoluteUvCount += rawObjectDescription.uvs.length;
  880. absoluteNormalCount += rawObjectDescription.normals.length;
  881. }
  882. }
  883. // do not continue if no result
  884. var result = null;
  885. if ( rawObjectDescriptionsTemp.length > 0 ) {
  886. result = {
  887. name: this.groupName !== '' ? this.groupName : this.objectName,
  888. subGroups: rawObjectDescriptionsTemp,
  889. absoluteVertexCount: absoluteVertexCount,
  890. absoluteIndexCount: absoluteIndexCount,
  891. absoluteColorCount: absoluteColorCount,
  892. absoluteNormalCount: absoluteNormalCount,
  893. absoluteUvCount: absoluteUvCount,
  894. faceCount: this.faceCount,
  895. doubleIndicesCount: this.doubleIndicesCount
  896. };
  897. }
  898. return result;
  899. };
  900. RawMesh.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  901. var report = {
  902. objectName: this.objectName,
  903. groupName: this.groupName,
  904. mtllibName: this.mtllibName,
  905. vertexCount: this.vertices.length / 3,
  906. normalCount: this.normals.length / 3,
  907. uvCount: this.uvs.length / 2,
  908. smoothingGroupCount: this.smoothingGroupCount,
  909. mtlCount: this.mtlCount,
  910. subGroups: this.subGroups.length
  911. };
  912. if ( printDirectly ) {
  913. console.log( 'Input Object number: ' + inputObjectCount +
  914. '\n\tObject name: ' + report.objectName +
  915. '\n\tGroup name: ' + report.groupName +
  916. '\n\tMtllib name: ' + report.mtllibName +
  917. '\n\tVertex count: ' + report.vertexCount +
  918. '\n\tNormal count: ' + report.normalCount +
  919. '\n\tUV count: ' + report.uvCount +
  920. '\n\tSmoothingGroup count: ' + report.smoothingGroupCount +
  921. '\n\tMaterial count: ' + report.mtlCount +
  922. '\n\tReal RawMeshSubGroup count: ' + report.subGroups
  923. );
  924. }
  925. return report;
  926. };
  927. return RawMesh;
  928. })();
  929. /**
  930. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  931. * @class
  932. *
  933. * @param {string} objectName Name of the mesh
  934. * @param {string} groupName Name of the group
  935. * @param {string} materialName Name of the material
  936. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  937. */
  938. var RawMeshSubGroup = (function () {
  939. function RawMeshSubGroup( objectName, groupName, materialName, smoothingGroup ) {
  940. this.objectName = objectName;
  941. this.groupName = groupName;
  942. this.materialName = materialName;
  943. this.smoothingGroup = smoothingGroup;
  944. this.vertices = [];
  945. this.indexMappingsCount = 0;
  946. this.indexMappings = [];
  947. this.indices = [];
  948. this.colors = [];
  949. this.uvs = [];
  950. this.normals = [];
  951. }
  952. return RawMeshSubGroup;
  953. })();
  954. OBJLoader2.prototype._checkFiles = function ( resources ) {
  955. var resource;
  956. var result = {
  957. mtl: null,
  958. obj: null
  959. };
  960. for ( var index in resources ) {
  961. resource = resources[ index ];
  962. if ( ! Validator.isValid( resource.name ) ) continue;
  963. if ( Validator.isValid( resource.content ) ) {
  964. if ( resource.extension === 'OBJ' ) {
  965. // fast-fail on bad type
  966. if ( ! ( resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type arraybuffer! Aborting...';
  967. result.obj = resource;
  968. } else if ( resource.extension === 'MTL' && Validator.isValid( resource.name ) ) {
  969. if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String ) ) throw 'Provided content is not of type String! Aborting...';
  970. result.mtl = resource;
  971. } else if ( resource.extension === "ZIP" ) {
  972. // ignore
  973. } else {
  974. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  975. }
  976. } else {
  977. // fast-fail on bad type
  978. if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
  979. if ( resource.extension === 'OBJ' ) {
  980. result.obj = resource;
  981. } else if ( resource.extension === 'MTL' ) {
  982. result.mtl = resource;
  983. } else if ( resource.extension === "ZIP" ) {
  984. // ignore
  985. } else {
  986. throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  987. }
  988. }
  989. }
  990. return result;
  991. };
  992. /**
  993. * Utility method for loading an mtl file according resource description.
  994. * @memberOf THREE.OBJLoader2
  995. *
  996. * @param {string} url URL to the file
  997. * @param {string} name The name of the object
  998. * @param {Object} content The file content as arraybuffer or text
  999. * @param {function} callbackOnLoad
  1000. * @param {string} [crossOrigin] CORS value
  1001. */
  1002. OBJLoader2.prototype.loadMtl = function ( url, name, content, callbackOnLoad, crossOrigin ) {
  1003. var resource = new THREE.LoaderSupport.ResourceDescriptor( url, 'MTL' );
  1004. resource.setContent( content );
  1005. this._loadMtl( resource, callbackOnLoad, crossOrigin );
  1006. };
  1007. /**
  1008. * Utility method for loading an mtl file according resource description.
  1009. * @memberOf THREE.OBJLoader2
  1010. *
  1011. * @param {THREE.LoaderSupport.ResourceDescriptor} resource
  1012. * @param {function} callbackOnLoad
  1013. * @param {string} [crossOrigin] CORS value
  1014. */
  1015. OBJLoader2.prototype._loadMtl = function ( resource, callbackOnLoad, crossOrigin ) {
  1016. if ( Validator.isValid( resource ) ) console.time( 'Loading MTL: ' + resource.name );
  1017. var materials = [];
  1018. var processMaterials = function ( materialCreator ) {
  1019. var materialCreatorMaterials = [];
  1020. if ( Validator.isValid( materialCreator ) ) {
  1021. materialCreator.preload();
  1022. materialCreatorMaterials = materialCreator.materials;
  1023. for ( var materialName in materialCreatorMaterials ) {
  1024. if ( materialCreatorMaterials.hasOwnProperty( materialName ) ) {
  1025. materials[ materialName ] = materialCreatorMaterials[ materialName ];
  1026. }
  1027. }
  1028. }
  1029. if ( Validator.isValid( resource ) ) console.timeEnd( 'Loading MTL: ' + resource.name );
  1030. callbackOnLoad( materials );
  1031. };
  1032. var mtlLoader = new THREE.MTLLoader();
  1033. crossOrigin = Validator.verifyInput( crossOrigin, 'anonymous' );
  1034. mtlLoader.setCrossOrigin( crossOrigin );
  1035. // fast-fail
  1036. if ( ! Validator.isValid( resource ) || ( ! Validator.isValid( resource.content ) && ! Validator.isValid( resource.url ) ) ) {
  1037. processMaterials();
  1038. } else {
  1039. mtlLoader.setPath( resource.path );
  1040. if ( Validator.isValid( resource.content ) ) {
  1041. processMaterials( Validator.isValid( resource.content ) ? mtlLoader.parse( resource.content ) : null );
  1042. } else if ( Validator.isValid( resource.url ) ) {
  1043. var onError = function ( event ) {
  1044. var output = 'Error occurred while downloading "' + resource.url + '"';
  1045. console.error( output + ': ' + event );
  1046. throw output;
  1047. };
  1048. mtlLoader.load( resource.name, processMaterials, undefined, onError );
  1049. }
  1050. }
  1051. };
  1052. return OBJLoader2;
  1053. })();