OBJLoader2.js 42 KB

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