OBJLoader2.js 45 KB

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