OBJLoader2.js 45 KB

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