OBJLoader2.js 44 KB

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