OBJLoader2.js 44 KB

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