2
0

OBJLoader2.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  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.2.1';
  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, that contain {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( 32 );
  227. var bufferPointer = 0;
  228. var slashes = new Array( 32 );
  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( 32 );
  269. var bufferPointer = 0;
  270. var slashes = new Array( 32 );
  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. switch ( buffer[ 0 ] ) {
  305. case Consts.LINE_V:
  306. // object complete instance required if reached faces already (= reached next block of v)
  307. if ( reachedFaces ) {
  308. this.processCompletedObject( null, this.rawObject.groupName );
  309. reachedFaces = false;
  310. }
  311. this.rawObject.pushVertex( buffer );
  312. break;
  313. case Consts.LINE_VT:
  314. this.rawObject.pushUv( buffer );
  315. break;
  316. case Consts.LINE_VN:
  317. this.rawObject.pushNormal( buffer );
  318. break;
  319. case Consts.LINE_F:
  320. reachedFaces = true;
  321. /*
  322. * 0: "f vertex/uv/normal ..."
  323. * 1: "f vertex/uv ..."
  324. * 2: "f vertex//normal ..."
  325. * 3: "f vertex ..."
  326. */
  327. var haveQuad = bufferLength % 4 === 0;
  328. if ( slashesPointer > 1 && ( slashes[ 1 ] - slashes[ 0 ] ) === 1 ) {
  329. if ( haveQuad ) {
  330. this.rawObject.buildQuadVVn( buffer );
  331. } else {
  332. this.rawObject.buildFaceVVn( buffer );
  333. }
  334. } else if ( bufferLength === slashesPointer * 2 ) {
  335. if ( haveQuad ) {
  336. this.rawObject.buildQuadVVt( buffer );
  337. } else {
  338. this.rawObject.buildFaceVVt( buffer );
  339. }
  340. } else if ( bufferLength * 2 === slashesPointer * 3 ) {
  341. if ( haveQuad ) {
  342. this.rawObject.buildQuadVVtVn( buffer );
  343. } else {
  344. this.rawObject.buildFaceVVtVn( buffer );
  345. }
  346. } else {
  347. if ( haveQuad ) {
  348. this.rawObject.buildQuadV( buffer );
  349. } else {
  350. this.rawObject.buildFaceV( buffer );
  351. }
  352. }
  353. break;
  354. case Consts.LINE_L:
  355. if ( bufferLength === slashesPointer * 2 ) {
  356. this.rawObject.buildLineVvt( buffer );
  357. } else {
  358. this.rawObject.buildLineV( buffer );
  359. }
  360. break;
  361. case Consts.LINE_S:
  362. this.rawObject.pushSmoothingGroup( buffer[ 1 ] );
  363. break;
  364. case Consts.LINE_G:
  365. this.processCompletedGroup( buffer[ 1 ] );
  366. break;
  367. case Consts.LINE_O:
  368. if ( this.rawObject.vertices.length > 0 ) {
  369. this.processCompletedObject( buffer[ 1 ], null );
  370. reachedFaces = false;
  371. } else {
  372. this.rawObject.pushObject( buffer[ 1 ] );
  373. }
  374. break;
  375. case Consts.LINE_MTLLIB:
  376. this.rawObject.pushMtllib( buffer[ 1 ] );
  377. break;
  378. case Consts.LINE_USEMTL:
  379. this.rawObject.pushUsemtl( buffer[ 1 ] );
  380. break;
  381. default:
  382. break;
  383. }
  384. return reachedFaces;
  385. };
  386. Parser.prototype.processCompletedObject = function ( objectName, groupName ) {
  387. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  388. this.inputObjectCount++;
  389. this.rawObject = this.rawObject.newInstanceFromObject( objectName, groupName );
  390. };
  391. Parser.prototype.processCompletedGroup = function ( groupName ) {
  392. var notEmpty = this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  393. if ( notEmpty ) {
  394. this.inputObjectCount ++;
  395. this.rawObject = this.rawObject.newInstanceFromGroup( groupName );
  396. } else {
  397. // if a group was set that did not lead to object creation in finalize, then the group name has to be updated
  398. this.rawObject.pushGroup( groupName );
  399. }
  400. };
  401. Parser.prototype.finalize = function () {
  402. this.rawObject.finalize( this.meshCreator, this.inputObjectCount, this.debug );
  403. this.inputObjectCount++;
  404. };
  405. return Parser;
  406. })();
  407. /**
  408. * {@link RawObject} is only used by {@link Parser}.
  409. * The user of OBJLoader2 does not need to care about this class.
  410. * It is defined publicly for inclusion in web worker based OBJ loader ({@link THREE.OBJLoader2.WWOBJLoader2})
  411. */
  412. var RawObject = (function () {
  413. function RawObject( objectName, groupName, mtllibName ) {
  414. this.globalVertexOffset = 1;
  415. this.globalUvOffset = 1;
  416. this.globalNormalOffset = 1;
  417. this.vertices = [];
  418. this.normals = [];
  419. this.uvs = [];
  420. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  421. this.mtllibName = Validator.verifyInput( mtllibName, 'none' );
  422. this.objectName = Validator.verifyInput( objectName, 'none' );
  423. this.groupName = Validator.verifyInput( groupName, 'none' );
  424. this.activeMtlName = 'none';
  425. this.activeSmoothingGroup = 1;
  426. this.mtlCount = 0;
  427. this.smoothingGroupCount = 0;
  428. this.rawObjectDescriptions = [];
  429. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  430. var index = this.buildIndex( this.activeMtlName, this.activeSmoothingGroup );
  431. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  432. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  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.uvs = this.uvs;
  450. newRawObject.normals = this.normals;
  451. newRawObject.globalVertexOffset = this.globalVertexOffset;
  452. newRawObject.globalUvOffset = this.globalUvOffset;
  453. newRawObject.globalNormalOffset = this.globalNormalOffset;
  454. return newRawObject;
  455. };
  456. RawObject.prototype.pushVertex = function ( buffer ) {
  457. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  458. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  459. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  460. };
  461. RawObject.prototype.pushUv = function ( buffer ) {
  462. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  463. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  464. };
  465. RawObject.prototype.pushNormal = function ( buffer ) {
  466. this.normals.push( parseFloat( buffer[ 1 ] ) );
  467. this.normals.push( parseFloat( buffer[ 2 ] ) );
  468. this.normals.push( parseFloat( buffer[ 3 ] ) );
  469. };
  470. RawObject.prototype.pushObject = function ( objectName ) {
  471. this.objectName = objectName;
  472. };
  473. RawObject.prototype.pushMtllib = function ( mtllibName ) {
  474. this.mtllibName = mtllibName;
  475. };
  476. RawObject.prototype.pushGroup = function ( groupName ) {
  477. this.groupName = groupName;
  478. this.verifyIndex();
  479. };
  480. RawObject.prototype.pushUsemtl = function ( mtlName ) {
  481. if ( this.activeMtlName === mtlName || ! Validator.isValid( mtlName ) ) return;
  482. this.activeMtlName = mtlName;
  483. this.mtlCount++;
  484. this.verifyIndex();
  485. };
  486. RawObject.prototype.pushSmoothingGroup = function ( activeSmoothingGroup ) {
  487. var normalized = activeSmoothingGroup === 'off' ? 0 : activeSmoothingGroup;
  488. if ( this.activeSmoothingGroup === normalized ) return;
  489. this.activeSmoothingGroup = normalized;
  490. this.smoothingGroupCount++;
  491. this.verifyIndex();
  492. };
  493. RawObject.prototype.verifyIndex = function () {
  494. var index = this.buildIndex( this.activeMtlName, ( this.activeSmoothingGroup === 0 ) ? 0 : 1 );
  495. this.rawObjectDescriptionInUse = this.rawObjectDescriptions[ index ];
  496. if ( ! Validator.isValid( this.rawObjectDescriptionInUse ) ) {
  497. this.rawObjectDescriptionInUse = new RawObjectDescription( this.objectName, this.groupName, this.activeMtlName, this.activeSmoothingGroup );
  498. this.rawObjectDescriptions[ index ] = this.rawObjectDescriptionInUse;
  499. }
  500. };
  501. RawObject.prototype.buildQuadVVtVn = function ( indexArray ) {
  502. for ( var i = 0; i < 6; i ++ ) {
  503. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_3[ i ] ] );
  504. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_3[ i ] + 1 ] );
  505. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_3[ i ] + 2 ] );
  506. }
  507. };
  508. RawObject.prototype.buildQuadVVt = function ( indexArray ) {
  509. for ( var i = 0; i < 6; i ++ ) {
  510. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  511. this.attachFaceVt( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  512. }
  513. };
  514. RawObject.prototype.buildQuadVVn = function ( indexArray ) {
  515. for ( var i = 0; i < 6; i ++ ) {
  516. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_2[ i ] ] );
  517. this.attachFaceVn( indexArray[ Consts.QUAD_INDICES_2[ i ] + 1 ] );
  518. }
  519. };
  520. RawObject.prototype.buildQuadV = function ( indexArray ) {
  521. for ( var i = 0; i < 6; i ++ ) {
  522. this.attachFaceV_( indexArray[ Consts.QUAD_INDICES_1[ i ] ] );
  523. }
  524. };
  525. RawObject.prototype.buildFaceVVtVn = function ( indexArray ) {
  526. for ( var i = 1; i < 10; i += 3 ) {
  527. this.attachFaceV_( indexArray[ i ] );
  528. this.attachFaceVt( indexArray[ i + 1 ] );
  529. this.attachFaceVn( indexArray[ i + 2 ] );
  530. }
  531. };
  532. RawObject.prototype.buildFaceVVt = function ( indexArray ) {
  533. for ( var i = 1; i < 7; i += 2 ) {
  534. this.attachFaceV_( indexArray[ i ] );
  535. this.attachFaceVt( indexArray[ i + 1 ] );
  536. }
  537. };
  538. RawObject.prototype.buildFaceVVn = function ( indexArray ) {
  539. for ( var i = 1; i < 7; i += 2 ) {
  540. this.attachFaceV_( indexArray[ i ] );
  541. this.attachFaceVn( indexArray[ i + 1 ] );
  542. }
  543. };
  544. RawObject.prototype.buildFaceV = function ( indexArray ) {
  545. for ( var i = 1; i < 4; i ++ ) {
  546. this.attachFaceV_( indexArray[ i ] );
  547. }
  548. };
  549. RawObject.prototype.attachFaceV_ = function ( faceIndex ) {
  550. var faceIndexInt = parseInt( faceIndex );
  551. var index = ( faceIndexInt - this.globalVertexOffset ) * 3;
  552. var rodiu = this.rawObjectDescriptionInUse;
  553. rodiu.vertices.push( this.vertices[ index++ ] );
  554. rodiu.vertices.push( this.vertices[ index++ ] );
  555. rodiu.vertices.push( this.vertices[ index ] );
  556. };
  557. RawObject.prototype.attachFaceVt = function ( faceIndex ) {
  558. var faceIndexInt = parseInt( faceIndex );
  559. var index = ( faceIndexInt - this.globalUvOffset ) * 2;
  560. var rodiu = this.rawObjectDescriptionInUse;
  561. rodiu.uvs.push( this.uvs[ index++ ] );
  562. rodiu.uvs.push( this.uvs[ index ] );
  563. };
  564. RawObject.prototype.attachFaceVn = function ( faceIndex ) {
  565. var faceIndexInt = parseInt( faceIndex );
  566. var index = ( faceIndexInt - this.globalNormalOffset ) * 3;
  567. var rodiu = this.rawObjectDescriptionInUse;
  568. rodiu.normals.push( this.normals[ index++ ] );
  569. rodiu.normals.push( this.normals[ index++ ] );
  570. rodiu.normals.push( this.normals[ index ] );
  571. };
  572. /*
  573. * Support for lines with or without texture. irst element in indexArray is the line identification
  574. * 0: "f vertex/uv vertex/uv ..."
  575. * 1: "f vertex vertex ..."
  576. */
  577. RawObject.prototype.buildLineVvt = function ( lineArray ) {
  578. var length = lineArray.length;
  579. for ( var i = 1; i < length; i ++ ) {
  580. this.vertices.push( parseInt( lineArray[ i ] ) );
  581. this.uvs.push( parseInt( lineArray[ i ] ) );
  582. }
  583. };
  584. RawObject.prototype.buildLineV = function ( lineArray ) {
  585. var length = lineArray.length;
  586. for ( var i = 1; i < length; i++ ) {
  587. this.vertices.push( parseInt( lineArray[ i ] ) );
  588. }
  589. };
  590. /**
  591. * Clear any empty rawObjectDescription and calculate absolute vertex, normal and uv counts
  592. */
  593. RawObject.prototype.finalize = function ( meshCreator, inputObjectCount, debug ) {
  594. var temp = this.rawObjectDescriptions;
  595. this.rawObjectDescriptions = [];
  596. var rawObjectDescription;
  597. var index = 0;
  598. var absoluteVertexCount = 0;
  599. var absoluteNormalCount = 0;
  600. var absoluteUvCount = 0;
  601. for ( var name in temp ) {
  602. rawObjectDescription = temp[ name ];
  603. if ( rawObjectDescription.vertices.length > 0 ) {
  604. if ( rawObjectDescription.objectName === 'none' ) rawObjectDescription.objectName = rawObjectDescription.groupName;
  605. this.rawObjectDescriptions[ index++ ] = rawObjectDescription;
  606. absoluteVertexCount += rawObjectDescription.vertices.length;
  607. absoluteUvCount += rawObjectDescription.uvs.length;
  608. absoluteNormalCount += rawObjectDescription.normals.length;
  609. }
  610. }
  611. // don not continue if no result
  612. var notEmpty = false;
  613. if ( index > 0 ) {
  614. if ( debug ) this.createReport( inputObjectCount, true );
  615. meshCreator.buildMesh(
  616. this.rawObjectDescriptions,
  617. inputObjectCount,
  618. absoluteVertexCount,
  619. absoluteNormalCount,
  620. absoluteUvCount
  621. );
  622. notEmpty = true;
  623. }
  624. return notEmpty;
  625. };
  626. RawObject.prototype.createReport = function ( inputObjectCount, printDirectly ) {
  627. var report = {
  628. name: this.objectName ? this.objectName : 'groups',
  629. mtllibName: this.mtllibName,
  630. vertexCount: this.vertices.length / 3,
  631. normalCount: this.normals.length / 3,
  632. uvCount: this.uvs.length / 2,
  633. smoothingGroupCount: this.smoothingGroupCount,
  634. mtlCount: this.mtlCount,
  635. rawObjectDescriptions: this.rawObjectDescriptions.length
  636. };
  637. if ( printDirectly ) {
  638. console.log( 'Input Object number: ' + inputObjectCount + ' Object name: ' + report.name );
  639. console.log( 'Mtllib name: ' + report.mtllibName );
  640. console.log( 'Vertex count: ' + report.vertexCount );
  641. console.log( 'Normal count: ' + report.normalCount );
  642. console.log( 'UV count: ' + report.uvCount );
  643. console.log( 'SmoothingGroup count: ' + report.smoothingGroupCount );
  644. console.log( 'Material count: ' + report.mtlCount );
  645. console.log( 'Real RawObjectDescription count: ' + report.rawObjectDescriptions );
  646. console.log( '' );
  647. }
  648. return report;
  649. };
  650. return RawObject;
  651. })();
  652. /**
  653. * Descriptive information and data (vertices, normals, uvs) to passed on to mesh building function.
  654. * @class
  655. *
  656. * @param {string} objectName Name of the mesh
  657. * @param {string} groupName Name of the group
  658. * @param {string} materialName Name of the material
  659. * @param {number} smoothingGroup Normalized smoothingGroup (0: THREE.FlatShading, 1: THREE.SmoothShading)
  660. */
  661. var RawObjectDescription = (function () {
  662. function RawObjectDescription( objectName, groupName, materialName, smoothingGroup ) {
  663. this.objectName = objectName;
  664. this.groupName = groupName;
  665. this.materialName = materialName;
  666. this.smoothingGroup = smoothingGroup;
  667. this.vertices = [];
  668. this.uvs = [];
  669. this.normals = [];
  670. }
  671. return RawObjectDescription;
  672. })();
  673. /**
  674. * MeshCreator is used to transform RawObjectDescriptions to THREE.Mesh
  675. *
  676. * @class
  677. */
  678. var MeshCreator = (function () {
  679. function MeshCreator() {
  680. this.sceneGraphBaseNode = null;
  681. this.materials = null;
  682. this.debug = false;
  683. this.globalObjectCount = 1;
  684. this.validated = false;
  685. }
  686. MeshCreator.prototype.setSceneGraphBaseNode = function ( sceneGraphBaseNode ) {
  687. this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, this.sceneGraphBaseNode );
  688. this.sceneGraphBaseNode = Validator.verifyInput( this.sceneGraphBaseNode, new THREE.Group() );
  689. };
  690. MeshCreator.prototype.setMaterials = function ( materials ) {
  691. this.materials = Validator.verifyInput( materials, this.materials );
  692. this.materials = Validator.verifyInput( this.materials, { materials: [] } );
  693. };
  694. MeshCreator.prototype.setDebug = function ( debug ) {
  695. if ( debug === true || debug === false ) this.debug = debug;
  696. };
  697. MeshCreator.prototype.validate = function () {
  698. if ( this.validated ) return;
  699. this.setSceneGraphBaseNode( null );
  700. this.setMaterials( null );
  701. this.setDebug( null );
  702. this.globalObjectCount = 1;
  703. };
  704. MeshCreator.prototype.finalize = function () {
  705. this.sceneGraphBaseNode = null;
  706. this.materials = null;
  707. this.validated = false;
  708. };
  709. /**
  710. * This is an internal function, but due to its importance to Parser it is documented.
  711. * RawObjectDescriptions are transformed to THREE.Mesh.
  712. * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
  713. * This method shall be overridden by the web worker implementation
  714. *
  715. * @param {RawObjectDescription[]} rawObjectDescriptions Array of descriptive information and data (vertices, normals, uvs) about the parsed object(s)
  716. * @param {number} inputObjectCount Number of objects already retrieved from OBJ
  717. * @param {number} absoluteVertexCount Sum of all vertices of all rawObjectDescriptions
  718. * @param {number} absoluteNormalCount Sum of all normals of all rawObjectDescriptions
  719. * @param {number} absoluteUvCount Sum of all uvs of all rawObjectDescriptions
  720. */
  721. MeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount, absoluteNormalCount, absoluteUvCount ) {
  722. if ( this.debug ) console.log( 'MeshCreator.buildRawMeshData:\nInput object no.: ' + inputObjectCount );
  723. var bufferGeometry = new THREE.BufferGeometry();
  724. var vertexBA = new THREE.BufferAttribute( new Float32Array( absoluteVertexCount ), 3 );
  725. bufferGeometry.addAttribute( 'position', vertexBA );
  726. var normalBA;
  727. if ( absoluteNormalCount > 0 ) {
  728. normalBA = new THREE.BufferAttribute( new Float32Array( absoluteNormalCount ), 3 );
  729. bufferGeometry.addAttribute( 'normal', normalBA );
  730. }
  731. var uvBA;
  732. if ( absoluteUvCount > 0 ) {
  733. uvBA = new THREE.BufferAttribute( new Float32Array( absoluteUvCount ), 2 );
  734. bufferGeometry.addAttribute( 'uv', uvBA );
  735. }
  736. if ( this.debug ) console.log( 'Creating Multi-Material for object no.: ' + this.globalObjectCount );
  737. var rawObjectDescription;
  738. var material;
  739. var materialName;
  740. var createMultiMaterial = rawObjectDescriptions.length > 1;
  741. var materials = [];
  742. var materialIndex = 0;
  743. var materialIndexMapping = [];
  744. var selectedMaterialIndex;
  745. var vertexBAOffset = 0;
  746. var vertexGroupOffset = 0;
  747. var vertexLength;
  748. var normalOffset = 0;
  749. var uvOffset = 0;
  750. for ( var oodIndex in rawObjectDescriptions ) {
  751. rawObjectDescription = rawObjectDescriptions[ oodIndex ];
  752. materialName = rawObjectDescription.materialName;
  753. material = this.materials[ materialName ];
  754. if ( ! material ) {
  755. material = this.materials[ 'defaultMaterial' ];
  756. if ( ! material ) {
  757. material = new THREE.MeshStandardMaterial( { color: 0xDCF1FF} );
  758. material.name = 'defaultMaterial';
  759. this.materials[ 'defaultMaterial' ] = material;
  760. }
  761. console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName + '" was defined without material! Assigning "defaultMaterial".' );
  762. }
  763. // clone material in case flat shading is needed due to smoothingGroup 0
  764. if ( rawObjectDescription.smoothingGroup === 0 ) {
  765. materialName = material.name + '_flat';
  766. var materialClone = this.materials[ materialName ];
  767. if ( ! materialClone ) {
  768. materialClone = material.clone();
  769. materialClone.name = materialName;
  770. materialClone.shading = THREE.FlatShading;
  771. this.materials[ materialName ] = name;
  772. }
  773. }
  774. vertexLength = rawObjectDescription.vertices.length;
  775. if ( createMultiMaterial ) {
  776. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  777. selectedMaterialIndex = materialIndexMapping[ materialName ];
  778. if ( ! selectedMaterialIndex ) {
  779. selectedMaterialIndex = materialIndex;
  780. materialIndexMapping[ materialName ] = materialIndex;
  781. materials.push( material );
  782. materialIndex++;
  783. }
  784. bufferGeometry.addGroup( vertexGroupOffset, vertexLength / 3, selectedMaterialIndex );
  785. vertexGroupOffset += vertexLength / 3;
  786. }
  787. vertexBA.set( rawObjectDescription.vertices, vertexBAOffset );
  788. vertexBAOffset += vertexLength;
  789. if ( normalBA ) {
  790. normalBA.set( rawObjectDescription.normals, normalOffset );
  791. normalOffset += rawObjectDescription.normals.length;
  792. }
  793. if ( uvBA ) {
  794. uvBA.set( rawObjectDescription.uvs, uvOffset );
  795. uvOffset += rawObjectDescription.uvs.length;
  796. }
  797. if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );
  798. }
  799. if ( ! normalBA ) bufferGeometry.computeVertexNormals();
  800. if ( createMultiMaterial ) material = materials;
  801. var mesh = new THREE.Mesh( bufferGeometry, material );
  802. this.sceneGraphBaseNode.add( mesh );
  803. this.globalObjectCount++;
  804. };
  805. MeshCreator.prototype.printReport = function ( rawObjectDescription, selectedMaterialIndex ) {
  806. console.log(
  807. ' Output Object no.: ' + this.globalObjectCount +
  808. '\n objectName: ' + rawObjectDescription.objectName +
  809. '\n groupName: ' + rawObjectDescription.groupName +
  810. '\n materialName: ' + rawObjectDescription.materialName +
  811. '\n materialIndex: ' + selectedMaterialIndex +
  812. '\n smoothingGroup: ' + rawObjectDescription.smoothingGroup +
  813. '\n #vertices: ' + rawObjectDescription.vertices.length / 3 +
  814. '\n #uvs: ' + rawObjectDescription.uvs.length / 2 +
  815. '\n #normals: ' + rawObjectDescription.normals.length / 3
  816. );
  817. };
  818. return MeshCreator;
  819. })();
  820. OBJLoader2.prototype._buildWebWorkerCode = function ( funcBuildObject, funcBuildSingelton ) {
  821. var workerCode = '';
  822. workerCode += funcBuildObject( 'Consts', Consts );
  823. workerCode += funcBuildObject( 'Validator', Validator );
  824. workerCode += funcBuildSingelton( 'Parser', 'Parser', Parser );
  825. workerCode += funcBuildSingelton( 'RawObject', 'RawObject', RawObject );
  826. workerCode += funcBuildSingelton( 'RawObjectDescription', 'RawObjectDescription', RawObjectDescription );
  827. return workerCode;
  828. };
  829. return OBJLoader2;
  830. })();