OBJLoader2.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.OBJLoader2 === undefined ) { THREE.OBJLoader2 = {} }
  7. /**
  8. * Use this class to load OBJ data from files or to parse OBJ data from arraybuffer or text
  9. * @class
  10. *
  11. * @param {THREE.DefaultLoadingManager} [manager] The loadingManager for the loader to use. Default is {@link THREE.DefaultLoadingManager}
  12. */
  13. THREE.OBJLoader2 = (function () {
  14. var OBJLOADER2_VERSION = '1.4.0';
  15. function OBJLoader2( manager ) {
  16. console.log( "Using THREE.OBJLoader2 version: " + OBJLOADER2_VERSION );
  17. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  18. this.path = '';
  19. this.fileLoader = new THREE.FileLoader( this.manager );
  20. this.meshCreator = new MeshCreator();
  21. this.parser = new Parser( this.meshCreator );
  22. this.validated = false;
  23. }
  24. /**
  25. * Base path to use.
  26. * @memberOf THREE.OBJLoader2
  27. *
  28. * @param {string} path The basepath
  29. */
  30. OBJLoader2.prototype.setPath = function ( path ) {
  31. this.path = Validator.verifyInput( path, this.path );
  32. };
  33. /**
  34. * Set the node where the loaded objects will be attached.
  35. * @memberOf THREE.OBJLoader2
  36. *
  37. * @param {THREE.Object3D} sceneGraphBaseNode Scenegraph object where meshes will be attached
  38. */
  39. OBJLoader2.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  40. this.meshCreator.setSceneGraphBaseNode( sceneGraphBaseNode );
  41. };
  42. /**
  43. * Set materials loaded by MTLLoader or any other supplier of an Array of {@link THREE.Material}.
  44. * @memberOf THREE.OBJLoader2
  45. *
  46. * @param {THREE.Material[]} materials Array of {@link THREE.Material} from MTLLoader
  47. */
  48. OBJLoader2.prototype.setMaterials = function ( materials ) {
  49. this.meshCreator.setMaterials( materials );
  50. };
  51. /**
  52. * Allows to set debug mode for the parser and the meshCreator.
  53. * @memberOf THREE.OBJLoader2
  54. *
  55. * @param {boolean} parserDebug Internal Parser will produce debug output
  56. * @param {boolean} meshCreatorDebug Internal MeshCreator will produce debug output
  57. */
  58. OBJLoader2.prototype.setDebug = function ( parserDebug, meshCreatorDebug ) {
  59. this.parser.setDebug( parserDebug );
  60. this.meshCreator.setDebug( meshCreatorDebug );
  61. };
  62. /**
  63. * Use this convenient method to load an OBJ file at the given URL. Per default the fileLoader uses an arraybuffer
  64. * @memberOf THREE.OBJLoader2
  65. *
  66. * @param {string} url URL of the file to load
  67. * @param {callback} onLoad Called after loading was successfully completed
  68. * @param {callback} onProgress Called to report progress of loading. The argument will be the XMLHttpRequest instance, which contains {integer total} and {integer loaded} bytes.
  69. * @param {callback} onError Called after an error occurred during loading
  70. * @param {boolean} [useArrayBuffer=true] Set this to false to force string based parsing
  71. */
  72. OBJLoader2.prototype.load = function ( url, onLoad, onProgress, onError, useArrayBuffer ) {
  73. this._validate();
  74. this.fileLoader.setPath( this.path );
  75. this.fileLoader.setResponseType( useArrayBuffer !== false ? 'arraybuffer' : 'text' );
  76. var scope = this;
  77. scope.fileLoader.load( url, function ( content ) {
  78. // only use parseText if useArrayBuffer is explicitly set to false
  79. onLoad( useArrayBuffer !== false ? scope.parse( content ) : scope.parseText( content ) );
  80. }, onProgress, onError );
  81. };
  82. /**
  83. * Default parse function: Parses OBJ file content stored in arrayBuffer and returns the sceneGraphBaseNode
  84. * @memberOf THREE.OBJLoader2
  85. *
  86. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  87. */
  88. OBJLoader2.prototype.parse = function ( arrayBuffer ) {
  89. // fast-fail on bad type
  90. if ( ! ( arrayBuffer instanceof ArrayBuffer || arrayBuffer instanceof Uint8Array ) ) {
  91. throw 'Provided input is not of type arraybuffer! Aborting...';
  92. }
  93. console.log( 'Parsing arrayBuffer...' );
  94. console.time( 'parseArrayBuffer' );
  95. this._validate();
  96. this.parser.parseArrayBuffer( arrayBuffer );
  97. var sceneGraphAttach = this._finalize();
  98. console.timeEnd( 'parseArrayBuffer' );
  99. return sceneGraphAttach;
  100. };
  101. /**
  102. * Legacy parse function: Parses OBJ file content stored in string and returns the sceneGraphBaseNode
  103. * @memberOf THREE.OBJLoader2
  104. *
  105. * @param {string} text OBJ data as string
  106. */
  107. OBJLoader2.prototype.parseText = function ( text ) {
  108. // fast-fail on bad type
  109. if ( ! ( typeof( text ) === 'string' || text instanceof String ) ) {
  110. throw 'Provided input is not of type String! Aborting...';
  111. }
  112. console.log( 'Parsing text...' );
  113. console.time( 'parseText' );
  114. this._validate();
  115. this.parser.parseText( text );
  116. var sceneGraphBaseNode = this._finalize();
  117. console.timeEnd( 'parseText' );
  118. return sceneGraphBaseNode;
  119. };
  120. OBJLoader2.prototype._validate = function () {
  121. if ( this.validated ) return;
  122. this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
  123. this.parser.validate();
  124. this.meshCreator.validate();
  125. this.validated = true;
  126. };
  127. OBJLoader2.prototype._finalize = function () {
  128. console.log( 'Global output object count: ' + this.meshCreator.globalObjectCount );
  129. this.parser.finalize();
  130. this.fileLoader = null;
  131. var sceneGraphBaseNode = this.meshCreator.sceneGraphBaseNode;
  132. this.meshCreator.finalize();
  133. this.validated = false;
  134. return sceneGraphBaseNode;
  135. };
  136. /**
  137. * Constants used by THREE.OBJLoader2
  138. */
  139. var Consts = {
  140. CODE_LF: 10,
  141. CODE_CR: 13,
  142. CODE_SPACE: 32,
  143. CODE_SLASH: 47,
  144. STRING_LF: '\n',
  145. STRING_CR: '\r',
  146. STRING_SPACE: ' ',
  147. STRING_SLASH: '/',
  148. LINE_F: 'f',
  149. LINE_G: 'g',
  150. LINE_L: 'l',
  151. LINE_O: 'o',
  152. LINE_S: 's',
  153. LINE_V: 'v',
  154. LINE_VT: 'vt',
  155. LINE_VN: 'vn',
  156. LINE_MTLLIB: 'mtllib',
  157. LINE_USEMTL: 'usemtl'
  158. };
  159. var Validator = {
  160. /**
  161. * If given input is null or undefined, false is returned otherwise true.
  162. *
  163. * @param input Anything
  164. * @returns {boolean}
  165. */
  166. isValid: function( input ) {
  167. return ( input !== null && input !== undefined );
  168. },
  169. /**
  170. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  171. *
  172. * @param input Anything
  173. * @param defaultValue Anything
  174. * @returns {*}
  175. */
  176. verifyInput: function( input, defaultValue ) {
  177. return ( input === null || input === undefined ) ? defaultValue : input;
  178. }
  179. };
  180. OBJLoader2.prototype._getValidator = function () {
  181. return Validator;
  182. };
  183. /**
  184. * Parse OBJ data either from ArrayBuffer or string
  185. * @class
  186. */
  187. var Parser = (function () {
  188. function Parser( meshCreator ) {
  189. this.meshCreator = meshCreator;
  190. this.rawObject = null;
  191. this.inputObjectCount = 1;
  192. this.debug = false;
  193. }
  194. Parser.prototype.setDebug = function ( debug ) {
  195. if ( debug === true || debug === false ) this.debug = debug;
  196. };
  197. Parser.prototype.validate = function () {
  198. this.rawObject = new RawObject();
  199. this.inputObjectCount = 1;
  200. };
  201. /**
  202. * Parse the provided arraybuffer
  203. * @memberOf Parser
  204. *
  205. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  206. */
  207. Parser.prototype.parseArrayBuffer = function ( arrayBuffer ) {
  208. var arrayBufferView = new Uint8Array( arrayBuffer );
  209. var length = arrayBufferView.byteLength;
  210. var buffer = new Array( 128 );
  211. var bufferPointer = 0;
  212. var slashesLast = 0;
  213. var slashesDistance = 0;
  214. var slashesCount = 0;
  215. var faceDescType = -1;
  216. var reachedFaces = false;
  217. var code;
  218. var word = '';
  219. for ( var i = 0; i < length; i++ ) {
  220. code = arrayBufferView[ i ];
  221. switch ( code ) {
  222. case Consts.CODE_SPACE:
  223. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  224. //Whenever space is reached after first block (f v/vn" ") and no face type has been calculated, it will be performed once
  225. if ( faceDescType === -1 && bufferPointer > 1 ) {
  226. faceDescType = ( slashesCount === 0 ) ? 3 : ( slashesCount === 1 ) ? 1 : ( slashesCount === 2 && slashesDistance === 1 ) ? 2 : 0;
  227. }
  228. word = '';
  229. break;
  230. case Consts.CODE_SLASH:
  231. if ( faceDescType === -1 ) {
  232. slashesCount++;
  233. slashesDistance = i - slashesLast;
  234. slashesLast = i;
  235. }
  236. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  237. word = '';
  238. break;
  239. case Consts.CODE_LF:
  240. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  241. word = '';
  242. reachedFaces = this.processLine( buffer, bufferPointer, faceDescType, reachedFaces );
  243. bufferPointer = 0;
  244. slashesLast = 0;
  245. slashesDistance = 0;
  246. slashesCount = 0;
  247. faceDescType = -1;
  248. break;
  249. case Consts.CODE_CR:
  250. break;
  251. default:
  252. word += String.fromCharCode( code );
  253. break;
  254. }
  255. }
  256. };
  257. /**
  258. * Parse the provided text
  259. * @memberOf Parser
  260. *
  261. * @param {string} text OBJ data as string
  262. */
  263. Parser.prototype.parseText = function ( text ) {
  264. var length = text.length;
  265. var buffer = new Array( 128 );
  266. var bufferPointer = 0;
  267. var slashesLast = 0;
  268. var slashesDistance = 0;
  269. var slashesCount = 0;
  270. var faceDescType = -1;
  271. var reachedFaces = false;
  272. var char;
  273. var word = '';
  274. for ( var i = 0; i < length; i++ ) {
  275. char = text[ i ];
  276. switch ( char ) {
  277. case Consts.STRING_SPACE:
  278. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  279. //Whenever space is reached after first block (f v/vn" ") and no face type has been calculated, it will be performed once
  280. if ( faceDescType === -1 && bufferPointer > 1 ) {
  281. faceDescType = ( slashesCount === 0 ) ? 3 : ( slashesCount === 1 ) ? 1 : ( slashesCount === 2 && slashesDistance === 1 ) ? 2 : 0;
  282. }
  283. word = '';
  284. break;
  285. case Consts.STRING_SLASH:
  286. if ( faceDescType === -1 ) {
  287. slashesCount++;
  288. slashesDistance = i - slashesLast;
  289. slashesLast = i;
  290. }
  291. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  292. word = '';
  293. break;
  294. case Consts.STRING_LF:
  295. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  296. word = '';
  297. reachedFaces = this.processLine( buffer, bufferPointer, faceDescType, reachedFaces );
  298. bufferPointer = 0;
  299. slashesLast = 0;
  300. slashesDistance = 0;
  301. slashesCount = 0;
  302. faceDescType = -1;
  303. break;
  304. case Consts.STRING_CR:
  305. break;
  306. default:
  307. word += char;
  308. }
  309. }
  310. };
  311. Parser.prototype.processLine = function ( buffer, bufferPointer, faceDescType, reachedFaces ) {
  312. if ( bufferPointer < 1 ) return reachedFaces;
  313. var bufferLength = bufferPointer - 1;
  314. var concatBuffer;
  315. switch ( buffer[ 0 ] ) {
  316. case Consts.LINE_V:
  317. // object complete instance required if reached faces already (= reached next block of v)
  318. if ( reachedFaces ) {
  319. if ( this.rawObject.colors.length > 0 && this.rawObject.colors.length !== this.rawObject.vertices.length ) {
  320. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  321. }
  322. this.processCompletedObject( null, this.rawObject.groupName );
  323. reachedFaces = false;
  324. }
  325. if ( bufferLength === 3 ) {
  326. this.rawObject.pushVertex( buffer )
  327. } else {
  328. this.rawObject.pushVertexAndVertextColors( buffer );
  329. }
  330. break;
  331. case Consts.LINE_VT:
  332. this.rawObject.pushUv( buffer );
  333. break;
  334. case Consts.LINE_VN:
  335. this.rawObject.pushNormal( buffer );
  336. break;
  337. case Consts.LINE_F:
  338. reachedFaces = true;
  339. this.rawObject.processFaces( buffer, bufferPointer, faceDescType );
  340. break;
  341. case Consts.LINE_L:
  342. if ( faceDescType === 1 ) {
  343. this.rawObject.buildLineVvt( buffer );
  344. } else {
  345. this.rawObject.buildLineV( buffer );
  346. }
  347. break;
  348. case Consts.LINE_S:
  349. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  350. this.flushStringBuffer( buffer, bufferPointer );
  351. break;
  352. case Consts.LINE_G:
  353. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  354. this.processCompletedGroup( concatBuffer );
  355. this.flushStringBuffer( buffer, bufferPointer );
  356. break;
  357. case Consts.LINE_O:
  358. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  359. if ( this.rawObject.vertices.length > 0 ) {
  360. this.processCompletedObject( concatBuffer, null );
  361. reachedFaces = false;
  362. } else {
  363. this.rawObject.pushObject( concatBuffer );
  364. }
  365. this.flushStringBuffer( buffer, bufferPointer );
  366. break;
  367. case Consts.LINE_MTLLIB:
  368. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  369. this.rawObject.pushMtllib( concatBuffer );
  370. this.flushStringBuffer( buffer, bufferPointer );
  371. break;
  372. case Consts.LINE_USEMTL:
  373. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  374. this.rawObject.pushUsemtl( concatBuffer );
  375. this.flushStringBuffer( buffer, bufferPointer );
  376. break;
  377. default:
  378. break;
  379. }
  380. return reachedFaces;
  381. };
  382. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  383. for ( var i = 0; i < bufferLength; i++ ) {
  384. buffer[ i ] = '';
  385. }
  386. };
  387. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  388. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  389. this.inputObjectCount++;
  390. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  391. };
  392. Parser.prototype.processCompletedGroup = function ( groupName ) {
  393. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  394. if ( notEmpty ) {
  395. this.inputObjectCount ++;
  396. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  397. } else {
  398. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  399. this.rawObject.pushGroup( groupName );
  400. }
  401. };
  402. Parser.prototype.finalize = function () {
  403. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  404. this.inputObjectCount++;
  405. };
  406. return Parser;
  407. })();
  408. /**
  409. * {@link RawObject} is only used by {@link Parser}.
  410. * The user of OBJLoader2 does not need to care about this class.
  411. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  412. */
  413. var RawObject = (function () {
  414. function RawObject( objectName, groupName, mtllibName ) {
  415. this.globalVertexOffset = 1;
  416. this.globalUvOffset = 1;
  417. this.globalNormalOffset = 1;
  418. this.vertices = [];
  419. this.colors = [];
  420. this.normals = [];
  421. this.uvs = [];
  422. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  423. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  424. this.objectName = Validator.verifyInput( objectName, '' );
  425. this.groupName = Validator.verifyInput( groupName, '' );
  426. this.activeMtlName = '';
  427. this.activeSmoothingGroup = 1;
  428. this.mtlCount = 0;
  429. this.smoothingGroupCount = 0;
  430. this.rawObjectDescriptions = [];
  431. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  432. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  433. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  434. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  435. }
  436. RawObject.prototype.buildIndex = function ( materialName, smoothingGroup) {
  437. return materialName + '|' + smoothingGroup;
  438. };
  439. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  440. var newRawObject = new RawObject( objectName, groupName, this.mtllibName );
  441. // move indices forward
  442. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  443. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  444. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  445. return newRawObject;
  446. };
  447. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  448. var newRawObject = new RawObject( this.objectName, groupName, this.mtllibName );
  449. // keep current buffers and indices forward
  450. newRawObject.vertices = this.vertices;
  451. newRawObject.colors = this.colors;
  452. newRawObject.uvs = this.uvs;
  453. newRawObject.normals = this.normals;
  454. newRawObject.globalVertexOffset = this.globalVertexOffset;
  455. newRawObject.globalUvOffset = this.globalUvOffset;
  456. newRawObject.globalNormalOffset = this.globalNormalOffset;
  457. return newRawObject;
  458. };
  459. RawObject.prototype.pushVertex = function ( buffer ) {
  460. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  461. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  462. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  463. };
  464. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  465. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  466. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  467. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  468. this.colors.push( parseFloat( buffer[ 4 ] ) );
  469. this.colors.push( parseFloat( buffer[ 5 ] ) );
  470. this.colors.push( parseFloat( buffer[ 6 ] ) );
  471. };
  472. RawObject.prototype.pushUv = function ( buffer ) {
  473. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  474. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  475. };
  476. RawObject.prototype.pushNormal = function ( buffer ) {
  477. this.normals.push( parseFloat( buffer[ 1 ] ) );
  478. this.normals.push( parseFloat( buffer[ 2 ] ) );
  479. this.normals.push( parseFloat( buffer[ 3 ] ) );
  480. };
  481. RawObject.prototype.pushObject = function ( objectName ) {
  482. this.objectName = objectName;
  483. };
  484. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  485. this.mtllibName = mtllibName;
  486. };
  487. RawObject.prototype.pushGroup = function ( groupName ) {
  488. this.groupName = groupName;
  489. this.verifyIndex();
  490. };
  491. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  492. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  493. this.activeMtlName = mtlName;
  494. this.mtlCount++;
  495. this.verifyIndex();
  496. };
  497. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  498. var normalized = parseInt( activeSmoothingGroup );
  499. if ( isNaN( normalized ) ) {
  500. normalized = activeSmoothingGroup === "off" ? 0 : 1;
  501. }
  502. if ( this.activeSmoothingGroup === normalized ) return;
  503. this.activeSmoothingGroup = normalized;
  504. this.smoothingGroupCount++;
  505. this.verifyIndex();
  506. };
  507. RawObject.prototype.verifyIndex = function () {
  508. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  509. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  510. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  511. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  512. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  513. }
  514. };
  515. RawObject.prototype.processFaces = function ( buffer, bufferPointer, faceDescType ) {
  516. var bufferLength = bufferPointer - 1;
  517. var i;
  518. switch ( faceDescType ) {
  519. // "f vertex/uv/normal ..."
  520. case 0:
  521. for ( i = 4; i < bufferLength - 3; i += 3 ) {
  522. this.attachFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  523. this.attachFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  524. this.attachFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  525. }
  526. break;
  527. // "f vertex/uv ..."
  528. case 1:
  529. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  530. this.attachFace( buffer[ 1 ], buffer[ 2 ] );
  531. this.attachFace( buffer[ i ], buffer[ i + 1 ] );
  532. this.attachFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  533. }
  534. break;
  535. // "f vertex//normal ..."
  536. case 2:
  537. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  538. this.attachFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  539. this.attachFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  540. this.attachFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  541. }
  542. break;
  543. // "f vertex ..."
  544. case 3:
  545. for ( i = 2; i < bufferLength - 1; i ++ ) {
  546. this.attachFace( buffer[ 1 ] );
  547. this.attachFace( buffer[ i ] );
  548. this.attachFace( buffer[ i + 1 ] );
  549. }
  550. break;
  551. default:
  552. break;
  553. }
  554. };
  555. RawObject.prototype.attachFace = function ( faceIndexV, faceIndexU, faceIndexN ) {
  556. var indexV = ( parseInt( faceIndexV ) - this.globalVertexOffset ) * 3;
  557. var vertices = this.rawObjectDescriptionInUse.vertices;
  558. vertices.push( this.vertices[ indexV ++ ] );
  559. vertices.push( this.vertices[ indexV ++ ] );
  560. vertices.push( this.vertices[ indexV ] );
  561. if ( this.colors.length > 0 ) {
  562. indexV -= 2;
  563. var colors = this.rawObjectDescriptionInUse.colors;
  564. colors.push( this.colors[ indexV ++ ] );
  565. colors.push( this.colors[ indexV ++ ] );
  566. colors.push( this.colors[ indexV ] );
  567. }
  568. if ( faceIndexU ) {
  569. var indexU = ( parseInt( faceIndexU ) - this.globalUvOffset ) * 2;
  570. var uvs = this.rawObjectDescriptionInUse.uvs;
  571. uvs.push( this.uvs[ indexU ++ ] );
  572. uvs.push( this.uvs[ indexU ] );
  573. }
  574. if ( faceIndexN ) {
  575. var indexN = ( parseInt( faceIndexN ) - this.globalNormalOffset ) * 3;
  576. var normals = this.rawObjectDescriptionInUse.normals;
  577. normals.push( this.normals[ indexN ++ ] );
  578. normals.push( this.normals[ indexN ++ ] );
  579. normals.push( this.normals[ indexN ] );
  580. }
  581. };
  582. /*
  583. * Support for lines with or without texture. irst element in indexArray is the line identification
  584. * 0: "f vertex/uv vertex/uv ..."
  585. * 1: "f vertex vertex ..."
  586. */
  587. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  588. var length = lineArray.length;
  589. for ( var i = 1; i < length; i ++ ) {
  590. this.vertices.push( parseInt( lineArray[ i ] ) );
  591. this.uvs.push( parseInt( lineArray[ i ] ) );
  592. }
  593. };
  594. RawObject.prototype.buildLineV = function ( lineArray ) {
  595. var length = lineArray.length;
  596. for ( var i = 1; i < length; i++ ) {
  597. this.vertices.push( parseInt( lineArray[ i ] ) );
  598. }
  599. };
  600. /**
  601. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  602. */
  603. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  604. var temp = this.rawObjectDescriptions;
  605. this.rawObjectDescriptions = [];
  606. var rawObjectDescription;
  607. var index = 0;
  608. var absoluteVertexCount = 0;
  609. var absoluteColorCount = 0;
  610. var absoluteNormalCount = 0;
  611. var absoluteUvCount = 0;
  612. for ( var name in temp ) {
  613. rawObjectDescription = temp[ name ];
  614. if ( rawObjectDescription.vertices.length > 0 ) {
  615. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  616. absoluteVertexCount += rawObjectDescription.vertices.length;
  617. absoluteColorCount += rawObjectDescription.colors.length;
  618. absoluteUvCount += rawObjectDescription.uvs.length;
  619. absoluteNormalCount += rawObjectDescription.normals.length;
  620. }
  621. }
  622. // don not continue if no result
  623. var notEmpty = false;
  624. if ( index > 0 ) {
  625. if ( debug ) this.createReport( inputObjectCount, true );
  626. meshCreator.buildMesh(
  627. this.rawObjectDescriptions,
  628. inputObjectCount,
  629. absoluteVertexCount,
  630. absoluteColorCount,
  631. absoluteNormalCount,
  632. absoluteUvCount
  633. );
  634. notEmpty = true;
  635. }
  636. return notEmpty;
  637. };
  638. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  639. var report = {
  640. name: this.objectName ? this.objectName : 'groups',
  641. mtllibName: this.mtllibName,
  642. vertexCount: this.vertices.length / 3,
  643. normalCount: this.normals.length / 3,
  644. uvCount: this.uvs.length / 2,
  645. smoothingGroupCount: this.smoothingGroupCount,
  646. mtlCount: this.mtlCount,
  647. rawObjectDescriptions: this.rawObjectDescriptions.length
  648. };
  649. if ( printDirectly ) {
  650. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  651. console.log( 'Mtllib name: ' + report.mtllibName );
  652. console.log( 'Vertex count: ' + report.vertexCount );
  653. console.log( 'Normal count: ' + report.normalCount );
  654. console.log( 'UV count: ' + report.uvCount );
  655. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  656. console.log( 'Material count: ' + report.mtlCount );
  657. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  658. console.log( '' );
  659. }
  660. return report;
  661. };
  662. return RawObject;
  663. })();
  664. /**
  665. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  666. * @class
  667. *
  668. * @param {string} objectName Name of the mesh
  669. * @param {string} groupName Name of the group
  670. * @param {string} materialName Name of the material
  671. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  672. */
  673. var RawObjectDescription = (function () {
  674. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  675. this.objectName = objectName;
  676. this.groupName = groupName;
  677. this.materialName = materialName;
  678. this.smoothingGroup = smoothingGroup;
  679. this.vertices = [];
  680. this.colors = [];
  681. this.uvs = [];
  682. this.normals = [];
  683. }
  684. return RawObjectDescription;
  685. })();
  686. /**
  687. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  688. *
  689. * @class
  690. */
  691. var MeshCreator = (function () {
  692. function MeshCreator() {
  693. this.sceneGraphBaseNode = null;
  694. this.materials = null;
  695. this.debug = false;
  696. this.globalObjectCount = 1;
  697. this.validated = false;
  698. }
  699. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  700. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  701. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  702. };
  703. MeshCreator.prototype.setMaterials = function ( materials ) {
  704. this.materials = Validator.verifyInput( materials, this.materials );
  705. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  706. var defaultMaterial = this.materials[ 'defaultMaterial' ];
  707. if ( ! defaultMaterial ) {
  708. defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  709. defaultMaterial.name = 'defaultMaterial';
  710. this.materials[ 'defaultMaterial' ] = defaultMaterial;
  711. }
  712. var vertexColorMaterial = this.materials[ 'vertexColorMaterial' ];
  713. if ( ! vertexColorMaterial ) {
  714. vertexColorMaterial = new THREE.MeshBasicMaterial( { color: 0xDCF1FF } );
  715. vertexColorMaterial.name = 'vertexColorMaterial';
  716. vertexColorMaterial.vertexColors = THREE.VertexColors;
  717. this.materials[ 'vertexColorMaterial' ] = vertexColorMaterial;
  718. }
  719. };
  720. MeshCreator.prototype.setDebug = function ( debug ) {
  721. if ( debug === true || debug === false ) this.debug = debug;
  722. };
  723. MeshCreator.prototype.validate = function () {
  724. if ( this.validated ) return;
  725. this.setSceneGraphBaseNode( null );
  726. this.setMaterials( null );
  727. this.setDebug( null );
  728. this.globalObjectCount = 1;
  729. };
  730. MeshCreator.prototype.finalize = function () {
  731. this.sceneGraphBaseNode = null;
  732. this.materials = null;
  733. this.validated = false;
  734. };
  735. /**
  736. * This is an internal function, but due to its importance to Parser it is documented.
  737. * RawObjectDescriptions are transformed to THREE.Mesh.
  738. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  739. * This method shall be overridden by the web worker implementation
  740. *
  741. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  742. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  743. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  744. * @param {number} absoluteColorCount Sum of all vertex colors of all rawObjectDescriptions
  745. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  746. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  747. */
  748. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount,
  749. absoluteColorCount, absoluteNormalCount, absoluteUvCount ) {
  750. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  751. var bufferGeometry = new THREE.BufferGeometry();
  752. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  753. bufferGeometry.addAttribute( 'position', vertexBA );
  754. var colorBA;
  755. if ( absoluteColorCount > 0 ) {
  756. colorBA = new THREE.BufferAttribute( new Float32Array( absoluteColorCount ), 3 );
  757. bufferGeometry.addAttribute( 'color', colorBA );
  758. }
  759. var normalBA;
  760. if ( absoluteNormalCount > 0 ) {
  761. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  762. bufferGeometry.addAttribute( 'normal', normalBA );
  763. }
  764. var uvBA;
  765. if ( absoluteUvCount > 0 ) {
  766. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  767. bufferGeometry.addAttribute( 'uv', uvBA );
  768. }
  769. var rawObjectDescription;
  770. var material;
  771. var materialName;
  772. var createMultiMaterial = rawObjectDescriptions.length > 1;
  773. var materials = [];
  774. var materialIndex = 0;
  775. var materialIndexMapping = [];
  776. var selectedMaterialIndex;
  777. var vertexBAOffset = 0;
  778. var vertexGroupOffset = 0;
  779. var vertexLength;
  780. var colorBAOffset = 0;
  781. var normalBAOffset = 0;
  782. var uvBAOffset = 0;
  783. if ( this.debug ) {
  784. console.log( createMultiMaterial ? 'Creating Multi-Material' : 'Creating Material' + ' for object no.: ' + this.globalObjectCount );
  785. }
  786. for ( var oodIndex in rawObjectDescriptions ) {
  787. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  788. materialName = rawObjectDescription.materialName;
  789. material = colorBA ? this.materials[ 'vertexColorMaterial' ] : this.materials[ materialName ];
  790. if ( ! material ) {
  791. material = this.materials[ 'defaultMaterial' ];
  792. if ( ! material ) console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName +
  793. '" was defined without material! Assigning "defaultMaterial".' );
  794. }
  795. // clone material in case flat shading is needed due to smoothingGroup 0
  796. if ( rawObjectDescription.smoothingGroup === 0 ) {
  797. materialName = material.name + '_flat';
  798. var materialClone = this.materials[ materialName ];
  799. if ( ! materialClone ) {
  800. materialClone = material.clone();
  801. materialClone.name = materialName;
  802. materialClone.flatShading = true;
  803. this.materials[ materialName ] = name;
  804. }
  805. }
  806. vertexLength = rawObjectDescription.vertices.length;
  807. if ( createMultiMaterial ) {
  808. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  809. selectedMaterialIndex = materialIndexMapping[ materialName ];
  810. if ( ! selectedMaterialIndex ) {
  811. selectedMaterialIndex = materialIndex;
  812. materialIndexMapping[ materialName ] = materialIndex;
  813. materials.push( material );
  814. materialIndex++;
  815. }
  816. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  817. vertexGroupOffset += vertexLength / 3;
  818. }
  819. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  820. vertexBAOffset += vertexLength;
  821. if ( colorBA ) {
  822. colorBA.set( rawObjectDescription.colors, colorBAOffset );
  823. colorBAOffset += rawObjectDescription.colors.length;
  824. }
  825. if ( normalBA ) {
  826. normalBA.set( rawObjectDescription.normals, normalBAOffset );
  827. normalBAOffset += rawObjectDescription.normals.length;
  828. }
  829. if ( uvBA ) {
  830. uvBA.set( rawObjectDescription.uvs, uvBAOffset );
  831. uvBAOffset += rawObjectDescription.uvs.length;
  832. }
  833. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  834. }
  835. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  836. if ( createMultiMaterial ) material = materials;
  837. var mesh = new THREE.Mesh( bufferGeometry, material );
  838. mesh.name = rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName;
  839. this.sceneGraphBaseNode.add( mesh );
  840. this.globalObjectCount++;
  841. };
  842. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  843. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n materialIndex: ' + selectedMaterialIndex : '';
  844. console.log(
  845. ' Output Object no.: ' + this.globalObjectCount +
  846. '\n objectName: ' + rawObjectDescription.objectName +
  847. '\n groupName: ' + rawObjectDescription.groupName +
  848. '\n materialName: ' + rawObjectDescription.materialName +
  849. materialIndexLine +
  850. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  851. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  852. '\n #colors: ' + rawObjectDescription.colors.length / 3 +
  853. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  854. '\n #normals: ' + rawObjectDescription.normals.length / 3
  855. );
  856. };
  857. return MeshCreator;
  858. })();
  859. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  860. var workerCode = '';
  861. workerCode += funcBuildObject( 'Consts', Consts );
  862. workerCode += funcBuildObject( 'Validator', Validator );
  863. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  864. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  865. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  866. return workerCode;
  867. };
  868. return OBJLoader2;
  869. })();