OBJLoader2.js 44 KB

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