OBJLoader2.js 44 KB

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