OBJLoader2.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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. * Build Face/Quad: first element in indexArray is the line identification, therefore offset of one needs to be taken into account
  160. * N-Gons are not supported
  161. * Quad Faces: FaceA: 0, 1, 2 FaceB: 2, 3, 0
  162. *
  163. * 0: "f vertex/uv/normal vertex/uv/normal vertex/uv/normal (vertex/uv/normal)"
  164. * 1: "f vertex/uv vertex/uv vertex/uv (vertex/uv )"
  165. * 2: "f vertex//normal vertex//normal vertex//normal (vertex//normal )"
  166. * 3: "f vertex vertex vertex (vertex )"
  167. *
  168. * @param indexArray
  169. * @param faceType
  170. */
  171. QUAD_INDICES_1: [ 1, 2, 3, 3, 4, 1 ],
  172. QUAD_INDICES_2: [ 1, 3, 5, 5, 7, 1 ],
  173. QUAD_INDICES_3: [ 1, 4, 7, 7, 10, 1 ]
  174. };
  175. var Validator = {
  176. /**
  177. * If given input is null or undefined, false is returned otherwise true.
  178. *
  179. * @param input Anything
  180. * @returns {boolean}
  181. */
  182. isValid: function( input ) {
  183. return ( input !== null && input !== undefined );
  184. },
  185. /**
  186. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  187. *
  188. * @param input Anything
  189. * @param defaultValue Anything
  190. * @returns {*}
  191. */
  192. verifyInput: function( input, defaultValue ) {
  193. return ( input === null || input === undefined ) ? defaultValue : input;
  194. }
  195. };
  196. OBJLoader2.prototype._getValidator = function () {
  197. return Validator;
  198. };
  199. /**
  200. * Parse OBJ data either from ArrayBuffer or string
  201. * @class
  202. */
  203. var Parser = (function () {
  204. function Parser( meshCreator ) {
  205. this.meshCreator = meshCreator;
  206. this.rawObject = null;
  207. this.inputObjectCount = 1;
  208. this.debug = false;
  209. }
  210. Parser.prototype.setDebug = function ( debug ) {
  211. if ( debug === true || debug === false ) this.debug = debug;
  212. };
  213. Parser.prototype.validate = function () {
  214. this.rawObject = new RawObject();
  215. this.inputObjectCount = 1;
  216. };
  217. /**
  218. * Parse the provided arraybuffer
  219. * @memberOf Parser
  220. *
  221. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  222. */
  223. Parser.prototype.parseArrayBuffer = function ( arrayBuffer ) {
  224. var arrayBufferView = new Uint8Array( arrayBuffer );
  225. var length = arrayBufferView.byteLength;
  226. var buffer = new Array( 128 );
  227. var bufferPointer = 0;
  228. var slashes = new Array( 128 );
  229. var slashesPointer = 0;
  230. var reachedFaces = false;
  231. var code;
  232. var word = '';
  233. for ( var i = 0; i < length; i++ ) {
  234. code = arrayBufferView[ i ];
  235. switch ( code ) {
  236. case Consts.CODE_SPACE:
  237. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  238. word = '';
  239. break;
  240. case Consts.CODE_SLASH:
  241. slashes[ slashesPointer++ ] = i;
  242. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  243. word = '';
  244. break;
  245. case Consts.CODE_LF:
  246. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  247. word = '';
  248. reachedFaces = this.processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  249. slashesPointer = 0;
  250. bufferPointer = 0;
  251. break;
  252. case Consts.CODE_CR:
  253. break;
  254. default:
  255. word += String.fromCharCode( code );
  256. break;
  257. }
  258. }
  259. };
  260. /**
  261. * Parse the provided text
  262. * @memberOf Parser
  263. *
  264. * @param {string} text OBJ data as string
  265. */
  266. Parser.prototype.parseText = function ( text ) {
  267. var length = text.length;
  268. var buffer = new Array( 128 );
  269. var bufferPointer = 0;
  270. var slashes = new Array( 128 );
  271. var slashesPointer = 0;
  272. var reachedFaces = false;
  273. var char;
  274. var word = '';
  275. for ( var i = 0; i < length; i++ ) {
  276. char = text[ i ];
  277. switch ( char ) {
  278. case Consts.STRING_SPACE:
  279. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  280. word = '';
  281. break;
  282. case Consts.STRING_SLASH:
  283. slashes[ slashesPointer++ ] = i;
  284. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  285. word = '';
  286. break;
  287. case Consts.STRING_LF:
  288. if ( word.length > 0 ) buffer[ bufferPointer++ ] = word;
  289. word = '';
  290. reachedFaces = this.processLine( buffer, bufferPointer, slashes, slashesPointer, reachedFaces );
  291. slashesPointer = 0;
  292. bufferPointer = 0;
  293. break;
  294. case Consts.STRING_CR:
  295. break;
  296. default:
  297. word += char;
  298. }
  299. }
  300. };
  301. Parser.prototype.processLine = function ( buffer, bufferPointer, slashes, slashesPointer, reachedFaces ) {
  302. if ( bufferPointer < 1 ) return reachedFaces;
  303. var bufferLength = bufferPointer - 1;
  304. var concatBuffer;
  305. switch ( buffer[ 0 ] ) {
  306. case Consts.LINE_V:
  307. // object complete instance required if reached faces already (= reached next block of v)
  308. if ( reachedFaces ) {
  309. if ( this.rawObject.colors.length > 0 && this.rawObject.colors.length !== this.rawObject.vertices.length ) {
  310. throw 'Vertex Colors were detected, but vertex count and color count do not match!';
  311. }
  312. this.processCompletedObject( null, this.rawObject.groupName );
  313. reachedFaces = false;
  314. }
  315. if ( bufferLength === 3 ) {
  316. this.rawObject.pushVertex( buffer )
  317. } else {
  318. this.rawObject.pushVertexAndVertextColors( buffer );
  319. }
  320. break;
  321. case Consts.LINE_VT:
  322. this.rawObject.pushUv( buffer );
  323. break;
  324. case Consts.LINE_VN:
  325. this.rawObject.pushNormal( buffer );
  326. break;
  327. case Consts.LINE_F:
  328. reachedFaces = true;
  329. /*
  330. * 0: "f vertex/uv/normal ..."
  331. * 1: "f vertex/uv ..."
  332. * 2: "f vertex//normal ..."
  333. * 3: "f vertex ..."
  334. */
  335. var faceDescType = ( slashesPointer > 1 && ( slashes[ 1 ] - slashes[ 0 ] ) === 1 ) ? 2 : ( bufferLength === slashesPointer * 2 ) ? 1 : ( bufferLength * 2 === slashesPointer * 3 ) ? 0 : 3;
  336. this.rawObject.processFaces( buffer, bufferPointer, faceDescType );
  337. break;
  338. case Consts.LINE_L:
  339. if ( bufferLength === slashesPointer * 2 ) {
  340. this.rawObject.buildLineVvt( buffer );
  341. } else {
  342. this.rawObject.buildLineV( buffer );
  343. }
  344. break;
  345. case Consts.LINE_S:
  346. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  347. this.flushStringBuffer( buffer, bufferPointer );
  348. break;
  349. case Consts.LINE_G:
  350. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  351. this.processCompletedGroup( concatBuffer );
  352. this.flushStringBuffer( buffer, bufferPointer );
  353. break;
  354. case Consts.LINE_O:
  355. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  356. if ( this.rawObject.vertices.length > 0 ) {
  357. this.processCompletedObject( concatBuffer, null );
  358. reachedFaces = false;
  359. } else {
  360. this.rawObject.pushObject( concatBuffer );
  361. }
  362. this.flushStringBuffer( buffer, bufferPointer );
  363. break;
  364. case Consts.LINE_MTLLIB:
  365. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  366. this.rawObject.pushMtllib( concatBuffer );
  367. this.flushStringBuffer( buffer, bufferPointer );
  368. break;
  369. case Consts.LINE_USEMTL:
  370. concatBuffer = bufferLength > 1 ? buffer.slice( 1, bufferPointer ).join( ' ' ) : buffer[ 1 ];
  371. this.rawObject.pushUsemtl( concatBuffer );
  372. this.flushStringBuffer( buffer, bufferPointer );
  373. break;
  374. default:
  375. break;
  376. }
  377. return reachedFaces;
  378. };
  379. Parser.prototype.flushStringBuffer = function ( buffer, bufferLength ) {
  380. for ( var i = 0; i < bufferLength; i++ ) {
  381. buffer[ i ] = '';
  382. }
  383. };
  384. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  385. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  386. this.inputObjectCount++;
  387. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  388. };
  389. Parser.prototype.processCompletedGroup = function ( groupName ) {
  390. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  391. if ( notEmpty ) {
  392. this.inputObjectCount ++;
  393. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  394. } else {
  395. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  396. this.rawObject.pushGroup( groupName );
  397. }
  398. };
  399. Parser.prototype.finalize = function () {
  400. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  401. this.inputObjectCount++;
  402. };
  403. return Parser;
  404. })();
  405. /**
  406. * {@link RawObject} is only used by {@link Parser}.
  407. * The user of OBJLoader2 does not need to care about this class.
  408. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  409. */
  410. var RawObject = (function () {
  411. function RawObject( objectName, groupName, mtllibName ) {
  412. this.globalVertexOffset = 1;
  413. this.globalUvOffset = 1;
  414. this.globalNormalOffset = 1;
  415. this.vertices = [];
  416. this.colors = [];
  417. this.normals = [];
  418. this.uvs = [];
  419. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  420. this.mtllibName = Validator.verifyInput( mtllibName, '' );
  421. this.objectName = Validator.verifyInput( objectName, '' );
  422. this.groupName = Validator.verifyInput( groupName, '' );
  423. this.activeMtlName = '';
  424. this.activeSmoothingGroup = 1;
  425. this.mtlCount = 0;
  426. this.smoothingGroupCount = 0;
  427. this.rawObjectDescriptions = [];
  428. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  429. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  430. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  431. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  432. this.facesBuffer = new Array( 128 );
  433. }
  434. RawObject.prototype.buildIndex = function ( materialName, smoothingGroup) {
  435. return materialName + '|' + smoothingGroup;
  436. };
  437. RawObject.prototype.newInstanceFromObject = function ( objectName, groupName ) {
  438. var newRawObject = new RawObject( objectName, groupName, this.mtllibName );
  439. // move indices forward
  440. newRawObject.globalVertexOffset = this.globalVertexOffset + this.vertices.length / 3;
  441. newRawObject.globalUvOffset = this.globalUvOffset + this.uvs.length / 2;
  442. newRawObject.globalNormalOffset = this.globalNormalOffset + this.normals.length / 3;
  443. return newRawObject;
  444. };
  445. RawObject.prototype.newInstanceFromGroup = function ( groupName ) {
  446. var newRawObject = new RawObject( this.objectName, groupName, this.mtllibName );
  447. // keep current buffers and indices forward
  448. newRawObject.vertices = this.vertices;
  449. newRawObject.colors = this.colors;
  450. newRawObject.uvs = this.uvs;
  451. newRawObject.normals = this.normals;
  452. newRawObject.globalVertexOffset = this.globalVertexOffset;
  453. newRawObject.globalUvOffset = this.globalUvOffset;
  454. newRawObject.globalNormalOffset = this.globalNormalOffset;
  455. return newRawObject;
  456. };
  457. RawObject.prototype.pushVertex = function ( buffer ) {
  458. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  459. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  460. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  461. };
  462. RawObject.prototype.pushVertexAndVertextColors = function ( buffer ) {
  463. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  464. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  465. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  466. this.colors.push( parseFloat( buffer[ 4 ] ) );
  467. this.colors.push( parseFloat( buffer[ 5 ] ) );
  468. this.colors.push( parseFloat( buffer[ 6 ] ) );
  469. };
  470. RawObject.prototype.pushUv = function ( buffer ) {
  471. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  472. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  473. };
  474. RawObject.prototype.pushNormal = function ( buffer ) {
  475. this.normals.push( parseFloat( buffer[ 1 ] ) );
  476. this.normals.push( parseFloat( buffer[ 2 ] ) );
  477. this.normals.push( parseFloat( buffer[ 3 ] ) );
  478. };
  479. RawObject.prototype.pushObject = function ( objectName ) {
  480. this.objectName = objectName;
  481. };
  482. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  483. this.mtllibName = mtllibName;
  484. };
  485. RawObject.prototype.pushGroup = function ( groupName ) {
  486. this.groupName = groupName;
  487. this.verifyIndex();
  488. };
  489. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  490. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  491. this.activeMtlName = mtlName;
  492. this.mtlCount++;
  493. this.verifyIndex();
  494. };
  495. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  496. var normalized = parseInt( activeSmoothingGroup );
  497. if ( isNaN( normalized ) ) {
  498. normalized = activeSmoothingGroup === "off" ? 0 : 1;
  499. }
  500. if ( this.activeSmoothingGroup === normalized ) return;
  501. this.activeSmoothingGroup = normalized;
  502. this.smoothingGroupCount++;
  503. this.verifyIndex();
  504. };
  505. RawObject.prototype.verifyIndex = function () {
  506. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  507. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  508. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  509. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  510. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  511. }
  512. };
  513. RawObject.prototype.processFaces = function ( buffer, bufferPointer, faceDescType ) {
  514. var bufferLength = bufferPointer - 1;
  515. var facesBuffer = this.facesBuffer;
  516. var i;
  517. for ( i = 1; i < bufferLength + 1; i++) {
  518. facesBuffer[ i ] = parseInt( buffer[ i ] );
  519. }
  520. /*
  521. * 0: "f vertex/uv/normal ..."
  522. * 1: "f vertex/uv ..."
  523. * 2: "f vertex//normal ..."
  524. * 3: "f vertex ..."
  525. */
  526. if ( faceDescType === 0 ) {
  527. for ( i = 4; i < bufferLength - 3; i += 3 ) {
  528. this.attachFace( facesBuffer[ 1 ], facesBuffer[ 2 ], facesBuffer[ 3 ] );
  529. this.attachFace( facesBuffer[ i ], facesBuffer[ i + 1 ], facesBuffer[ i + 2 ] );
  530. this.attachFace( facesBuffer[ i + 3 ], facesBuffer[ i + 4 ], facesBuffer[ i + 5 ] );
  531. }
  532. } else if ( faceDescType === 1 ) {
  533. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  534. this.attachFace( facesBuffer[ 1 ], facesBuffer[ 2 ], -1 );
  535. this.attachFace( facesBuffer[ i ], facesBuffer[ i + 1 ], -1 );
  536. this.attachFace( facesBuffer[ i + 2 ], facesBuffer[ i + 3 ], -1 );
  537. }
  538. } else if ( faceDescType === 2 ) {
  539. for ( i = 3; i < bufferLength - 2; i += 2 ) {
  540. this.attachFace( facesBuffer[ 1 ], -1, facesBuffer[ 2 ] );
  541. this.attachFace( facesBuffer[ i ], -1, facesBuffer[ i + 1 ] );
  542. this.attachFace( facesBuffer[ i + 2 ], -1, facesBuffer[ i + 3 ] );
  543. }
  544. } else {
  545. for ( i = 2; i < bufferLength - 1; i ++ ) {
  546. this.attachFace( facesBuffer[ 1 ], -1, -1 );
  547. this.attachFace( facesBuffer[ i ], -1, -1 );
  548. this.attachFace( facesBuffer[ i + 1 ], -1, -1 );
  549. }
  550. }
  551. };
  552. RawObject.prototype.attachFace = function ( faceIndexV, faceIndexVt, faceIndexVn ) {
  553. var indexV = ( faceIndexV - this.globalVertexOffset ) * 3;
  554. var vertices = this.rawObjectDescriptionInUse.vertices;
  555. vertices.push( this.vertices[ indexV++ ] );
  556. vertices.push( this.vertices[ indexV++ ] );
  557. vertices.push( this.vertices[ indexV ] );
  558. if ( this.colors.length > 0 ) {
  559. indexV -= 2;
  560. var colors = this.rawObjectDescriptionInUse.colors;
  561. colors.push( this.colors[ indexV++ ] );
  562. colors.push( this.colors[ indexV++ ] );
  563. colors.push( this.colors[ indexV ] );
  564. }
  565. if ( faceIndexVt > -1 ) {
  566. var indexVt = ( faceIndexVt - this.globalUvOffset ) * 2;
  567. var uvs = this.rawObjectDescriptionInUse.uvs;
  568. uvs.push( this.uvs[ indexVt++ ] );
  569. uvs.push( this.uvs[ indexVt ] );
  570. }
  571. if ( faceIndexVn > -1 ) {
  572. var indexVn = ( faceIndexVn - this.globalNormalOffset ) * 3;
  573. var normals = this.rawObjectDescriptionInUse.normals;
  574. normals.push( this.normals[ indexVn ++ ] );
  575. normals.push( this.normals[ indexVn ++ ] );
  576. normals.push( this.normals[ indexVn ] );
  577. }
  578. };
  579. /*
  580. * Support for lines with or without texture. irst element in indexArray is the line identification
  581. * 0: "f vertex/uv vertex/uv ..."
  582. * 1: "f vertex vertex ..."
  583. */
  584. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  585. var length = lineArray.length;
  586. for ( var i = 1; i < length; i ++ ) {
  587. this.vertices.push( parseInt( lineArray[ i ] ) );
  588. this.uvs.push( parseInt( lineArray[ i ] ) );
  589. }
  590. };
  591. RawObject.prototype.buildLineV = function ( lineArray ) {
  592. var length = lineArray.length;
  593. for ( var i = 1; i < length; i++ ) {
  594. this.vertices.push( parseInt( lineArray[ i ] ) );
  595. }
  596. };
  597. /**
  598. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  599. */
  600. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  601. var temp = this.rawObjectDescriptions;
  602. this.rawObjectDescriptions = [];
  603. var rawObjectDescription;
  604. var index = 0;
  605. var absoluteVertexCount = 0;
  606. var absoluteColorCount = 0;
  607. var absoluteNormalCount = 0;
  608. var absoluteUvCount = 0;
  609. for ( var name in temp ) {
  610. rawObjectDescription = temp[ name ];
  611. if ( rawObjectDescription.vertices.length > 0 ) {
  612. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  613. absoluteVertexCount += rawObjectDescription.vertices.length;
  614. absoluteColorCount += rawObjectDescription.colors.length;
  615. absoluteUvCount += rawObjectDescription.uvs.length;
  616. absoluteNormalCount += rawObjectDescription.normals.length;
  617. }
  618. }
  619. // don not continue if no result
  620. var notEmpty = false;
  621. if ( index > 0 ) {
  622. if ( debug ) this.createReport( inputObjectCount, true );
  623. meshCreator.buildMesh(
  624. this.rawObjectDescriptions,
  625. inputObjectCount,
  626. absoluteVertexCount,
  627. absoluteColorCount,
  628. absoluteNormalCount,
  629. absoluteUvCount
  630. );
  631. notEmpty = true;
  632. }
  633. return notEmpty;
  634. };
  635. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  636. var report = {
  637. name: this.objectName ? this.objectName : 'groups',
  638. mtllibName: this.mtllibName,
  639. vertexCount: this.vertices.length / 3,
  640. normalCount: this.normals.length / 3,
  641. uvCount: this.uvs.length / 2,
  642. smoothingGroupCount: this.smoothingGroupCount,
  643. mtlCount: this.mtlCount,
  644. rawObjectDescriptions: this.rawObjectDescriptions.length
  645. };
  646. if ( printDirectly ) {
  647. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  648. console.log( 'Mtllib name: ' + report.mtllibName );
  649. console.log( 'Vertex count: ' + report.vertexCount );
  650. console.log( 'Normal count: ' + report.normalCount );
  651. console.log( 'UV count: ' + report.uvCount );
  652. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  653. console.log( 'Material count: ' + report.mtlCount );
  654. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  655. console.log( '' );
  656. }
  657. return report;
  658. };
  659. return RawObject;
  660. })();
  661. /**
  662. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  663. * @class
  664. *
  665. * @param {string} objectName Name of the mesh
  666. * @param {string} groupName Name of the group
  667. * @param {string} materialName Name of the material
  668. * @param {number} smoothingGroup Normalized smoothingGroup (0: flat shading, 1: smooth shading)
  669. */
  670. var RawObjectDescription = (function () {
  671. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  672. this.objectName = objectName;
  673. this.groupName = groupName;
  674. this.materialName = materialName;
  675. this.smoothingGroup = smoothingGroup;
  676. this.vertices = [];
  677. this.colors = [];
  678. this.uvs = [];
  679. this.normals = [];
  680. }
  681. return RawObjectDescription;
  682. })();
  683. /**
  684. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  685. *
  686. * @class
  687. */
  688. var MeshCreator = (function () {
  689. function MeshCreator() {
  690. this.sceneGraphBaseNode = null;
  691. this.materials = null;
  692. this.debug = false;
  693. this.globalObjectCount = 1;
  694. this.validated = false;
  695. }
  696. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  697. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  698. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  699. };
  700. MeshCreator.prototype.setMaterials = function ( materials ) {
  701. this.materials = Validator.verifyInput( materials, this.materials );
  702. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  703. var defaultMaterial = this.materials[ 'defaultMaterial' ];
  704. if ( ! defaultMaterial ) {
  705. defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  706. defaultMaterial.name = 'defaultMaterial';
  707. this.materials[ 'defaultMaterial' ] = defaultMaterial;
  708. }
  709. var vertexColorMaterial = this.materials[ 'vertexColorMaterial' ];
  710. if ( ! vertexColorMaterial ) {
  711. vertexColorMaterial = new THREE.MeshBasicMaterial( { color: 0xDCF1FF } );
  712. vertexColorMaterial.name = 'vertexColorMaterial';
  713. vertexColorMaterial.vertexColors = THREE.VertexColors;
  714. this.materials[ 'vertexColorMaterial' ] = vertexColorMaterial;
  715. }
  716. };
  717. MeshCreator.prototype.setDebug = function ( debug ) {
  718. if ( debug === true || debug === false ) this.debug = debug;
  719. };
  720. MeshCreator.prototype.validate = function () {
  721. if ( this.validated ) return;
  722. this.setSceneGraphBaseNode( null );
  723. this.setMaterials( null );
  724. this.setDebug( null );
  725. this.globalObjectCount = 1;
  726. };
  727. MeshCreator.prototype.finalize = function () {
  728. this.sceneGraphBaseNode = null;
  729. this.materials = null;
  730. this.validated = false;
  731. };
  732. /**
  733. * This is an internal function, but due to its importance to Parser it is documented.
  734. * RawObjectDescriptions are transformed to THREE.Mesh.
  735. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  736. * This method shall be overridden by the web worker implementation
  737. *
  738. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  739. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  740. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  741. * @param {number} absoluteColorCount Sum of all vertex colors of all rawObjectDescriptions
  742. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  743. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  744. */
  745. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount,
  746. absoluteColorCount, absoluteNormalCount, absoluteUvCount ) {
  747. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  748. var bufferGeometry = new THREE.BufferGeometry();
  749. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  750. bufferGeometry.addAttribute( 'position', vertexBA );
  751. var colorBA;
  752. if ( absoluteColorCount > 0 ) {
  753. colorBA = new THREE.BufferAttribute( new Float32Array( absoluteColorCount ), 3 );
  754. bufferGeometry.addAttribute( 'color', colorBA );
  755. }
  756. var normalBA;
  757. if ( absoluteNormalCount > 0 ) {
  758. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  759. bufferGeometry.addAttribute( 'normal', normalBA );
  760. }
  761. var uvBA;
  762. if ( absoluteUvCount > 0 ) {
  763. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  764. bufferGeometry.addAttribute( 'uv', uvBA );
  765. }
  766. var rawObjectDescription;
  767. var material;
  768. var materialName;
  769. var createMultiMaterial = rawObjectDescriptions.length > 1;
  770. var materials = [];
  771. var materialIndex = 0;
  772. var materialIndexMapping = [];
  773. var selectedMaterialIndex;
  774. var vertexBAOffset = 0;
  775. var vertexGroupOffset = 0;
  776. var vertexLength;
  777. var colorBAOffset = 0;
  778. var normalBAOffset = 0;
  779. var uvBAOffset = 0;
  780. if ( this.debug ) {
  781. console.log( createMultiMaterial ? 'Creating Multi-Material' : 'Creating Material' + ' for object no.: ' + this.globalObjectCount );
  782. }
  783. for ( var oodIndex in rawObjectDescriptions ) {
  784. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  785. materialName = rawObjectDescription.materialName;
  786. material = colorBA ? this.materials[ 'vertexColorMaterial' ] : this.materials[ materialName ];
  787. if ( ! material ) {
  788. material = this.materials[ 'defaultMaterial' ];
  789. if ( ! material ) console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName +
  790. '" was defined without material! Assigning "defaultMaterial".' );
  791. }
  792. // clone material in case flat shading is needed due to smoothingGroup 0
  793. if ( rawObjectDescription.smoothingGroup === 0 ) {
  794. materialName = material.name + '_flat';
  795. var materialClone = this.materials[ materialName ];
  796. if ( ! materialClone ) {
  797. materialClone = material.clone();
  798. materialClone.name = materialName;
  799. materialClone.flatShading = true;
  800. this.materials[ materialName ] = name;
  801. }
  802. }
  803. vertexLength = rawObjectDescription.vertices.length;
  804. if ( createMultiMaterial ) {
  805. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  806. selectedMaterialIndex = materialIndexMapping[ materialName ];
  807. if ( ! selectedMaterialIndex ) {
  808. selectedMaterialIndex = materialIndex;
  809. materialIndexMapping[ materialName ] = materialIndex;
  810. materials.push( material );
  811. materialIndex++;
  812. }
  813. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  814. vertexGroupOffset += vertexLength / 3;
  815. }
  816. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  817. vertexBAOffset += vertexLength;
  818. if ( colorBA ) {
  819. colorBA.set( rawObjectDescription.colors, colorBAOffset );
  820. colorBAOffset += rawObjectDescription.colors.length;
  821. }
  822. if ( normalBA ) {
  823. normalBA.set( rawObjectDescription.normals, normalBAOffset );
  824. normalBAOffset += rawObjectDescription.normals.length;
  825. }
  826. if ( uvBA ) {
  827. uvBA.set( rawObjectDescription.uvs, uvBAOffset );
  828. uvBAOffset += rawObjectDescription.uvs.length;
  829. }
  830. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  831. }
  832. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  833. if ( createMultiMaterial ) material = materials;
  834. var mesh = new THREE.Mesh( bufferGeometry, material );
  835. mesh.name = rawObjectDescription.groupName !== '' ? rawObjectDescription.groupName : rawObjectDescription.objectName;
  836. this.sceneGraphBaseNode.add( mesh );
  837. this.globalObjectCount++;
  838. };
  839. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  840. var materialIndexLine = Validator.isValid( selectedMaterialIndex ) ? '\n materialIndex: ' + selectedMaterialIndex : '';
  841. console.log(
  842. ' Output Object no.: ' + this.globalObjectCount +
  843. '\n objectName: ' + rawObjectDescription.objectName +
  844. '\n groupName: ' + rawObjectDescription.groupName +
  845. '\n materialName: ' + rawObjectDescription.materialName +
  846. materialIndexLine +
  847. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  848. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  849. '\n #colors: ' + rawObjectDescription.colors.length / 3 +
  850. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  851. '\n #normals: ' + rawObjectDescription.normals.length / 3
  852. );
  853. };
  854. return MeshCreator;
  855. })();
  856. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  857. var workerCode = '';
  858. workerCode += funcBuildObject( 'Consts', Consts );
  859. workerCode += funcBuildObject( 'Validator', Validator );
  860. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  861. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  862. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  863. return workerCode;
  864. };
  865. return OBJLoader2;
  866. })();