OBJLoader2.js 46 KB

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