OBJLoader2Parser.js 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. /**
  2. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  3. */
  4. /**
  5. * Parse OBJ data either from ArrayBuffer or string
  6. */
  7. const OBJLoader2Parser = function () {
  8. this.logging = {
  9. enabled: false,
  10. debug: false
  11. };
  12. const scope = this;
  13. this.callbacks = {
  14. onProgress: function ( text ) {
  15. scope._onProgress( text );
  16. },
  17. onAssetAvailable: function ( payload ) {
  18. scope._onAssetAvailable( payload );
  19. },
  20. onError: function ( errorMessage ) {
  21. scope._onError( errorMessage );
  22. },
  23. onLoad: function ( object3d, message ) {
  24. scope._onLoad( object3d, message );
  25. },
  26. };
  27. this.contentRef = null;
  28. this.legacyMode = false;
  29. this.materials = {};
  30. this.materialPerSmoothingGroup = false;
  31. this.useOAsMesh = false;
  32. this.useIndices = false;
  33. this.disregardNormals = false;
  34. this.vertices = [];
  35. this.colors = [];
  36. this.normals = [];
  37. this.uvs = [];
  38. this.rawMesh = {
  39. objectName: '',
  40. groupName: '',
  41. activeMtlName: '',
  42. mtllibName: '',
  43. // reset with new mesh
  44. faceType: - 1,
  45. subGroups: [],
  46. subGroupInUse: null,
  47. smoothingGroup: {
  48. splitMaterials: false,
  49. normalized: - 1,
  50. real: - 1
  51. },
  52. counts: {
  53. doubleIndicesCount: 0,
  54. faceCount: 0,
  55. mtlCount: 0,
  56. smoothingGroupCount: 0
  57. }
  58. };
  59. this.inputObjectCount = 1;
  60. this.outputObjectCount = 1;
  61. this.globalCounts = {
  62. vertices: 0,
  63. faces: 0,
  64. doubleIndicesCount: 0,
  65. lineByte: 0,
  66. currentByte: 0,
  67. totalBytes: 0
  68. };
  69. };
  70. OBJLoader2Parser.prototype = {
  71. constructor: OBJLoader2Parser,
  72. _resetRawMesh: function () {
  73. // faces are stored according combined index of group, material and smoothingGroup (0 or not)
  74. this.rawMesh.subGroups = [];
  75. this.rawMesh.subGroupInUse = null;
  76. this.rawMesh.smoothingGroup.normalized = - 1;
  77. this.rawMesh.smoothingGroup.real = - 1;
  78. // this default index is required as it is possible to define faces without 'g' or 'usemtl'
  79. this._pushSmoothingGroup( 1 );
  80. this.rawMesh.counts.doubleIndicesCount = 0;
  81. this.rawMesh.counts.faceCount = 0;
  82. this.rawMesh.counts.mtlCount = 0;
  83. this.rawMesh.counts.smoothingGroupCount = 0;
  84. },
  85. /**
  86. * Tells whether a material shall be created per smoothing group.
  87. *
  88. * @param {boolean} materialPerSmoothingGroup=false
  89. * @return {OBJLoader2Parser}
  90. */
  91. setMaterialPerSmoothingGroup: function ( materialPerSmoothingGroup ) {
  92. this.materialPerSmoothingGroup = materialPerSmoothingGroup === true;
  93. return this;
  94. },
  95. /**
  96. * Usually 'o' is meta-information and does not result in creation of new meshes, but mesh creation on occurrence of "o" can be enforced.
  97. *
  98. * @param {boolean} useOAsMesh=false
  99. * @return {OBJLoader2Parser}
  100. */
  101. setUseOAsMesh: function ( useOAsMesh ) {
  102. this.useOAsMesh = useOAsMesh === true;
  103. return this;
  104. },
  105. /**
  106. * Instructs loaders to create indexed {@link BufferGeometry}.
  107. *
  108. * @param {boolean} useIndices=false
  109. * @return {OBJLoader2Parser}
  110. */
  111. setUseIndices: function ( useIndices ) {
  112. this.useIndices = useIndices === true;
  113. return this;
  114. },
  115. /**
  116. * Tells whether normals should be completely disregarded and regenerated.
  117. *
  118. * @param {boolean} disregardNormals=false
  119. * @return {OBJLoader2Parser}
  120. */
  121. setDisregardNormals: function ( disregardNormals ) {
  122. this.disregardNormals = disregardNormals === true;
  123. return this;
  124. },
  125. /**
  126. * Clears materials object and sets the new ones.
  127. *
  128. * @param {Object} materials Object with named materials
  129. */
  130. setMaterials: function ( materials ) {
  131. this.materials = Object.assign( {}, materials );
  132. },
  133. /**
  134. * Register a function that is called once an asset (mesh/material) becomes available.
  135. *
  136. * @param onAssetAvailable
  137. * @return {OBJLoader2Parser}
  138. */
  139. setCallbackOnAssetAvailable: function ( onAssetAvailable ) {
  140. if ( onAssetAvailable !== null && onAssetAvailable !== undefined && onAssetAvailable instanceof Function ) {
  141. this.callbacks.onAssetAvailable = onAssetAvailable;
  142. }
  143. return this;
  144. },
  145. /**
  146. * Register a function that is used to report overall processing progress.
  147. *
  148. * @param {Function} onProgress
  149. * @return {OBJLoader2Parser}
  150. */
  151. setCallbackOnProgress: function ( onProgress ) {
  152. if ( onProgress !== null && onProgress !== undefined && onProgress instanceof Function ) {
  153. this.callbacks.onProgress = onProgress;
  154. }
  155. return this;
  156. },
  157. /**
  158. * Register an error handler function that is called if errors occur. It can decide to just log or to throw an exception.
  159. *
  160. * @param {Function} onError
  161. * @return {OBJLoader2Parser}
  162. */
  163. setCallbackOnError: function ( onError ) {
  164. if ( onError !== null && onError !== undefined && onError instanceof Function ) {
  165. this.callbacks.onError = onError;
  166. }
  167. return this;
  168. },
  169. /**
  170. * Register a function that is called when parsing was completed.
  171. *
  172. * @param {Function} onLoad
  173. * @return {OBJLoader2Parser}
  174. */
  175. setCallbackOnLoad: function ( onLoad ) {
  176. if ( onLoad !== null && onLoad !== undefined && onLoad instanceof Function ) {
  177. this.callbacks.onLoad = onLoad;
  178. }
  179. return this;
  180. },
  181. /**
  182. * Announce parse progress feedback which is logged to the console.
  183. * @private
  184. *
  185. * @param {string} text Textual description of the event
  186. */
  187. _onProgress: function ( text ) {
  188. const message = text ? text : '';
  189. if ( this.logging.enabled && this.logging.debug ) {
  190. console.log( message );
  191. }
  192. },
  193. /**
  194. * Announce error feedback which is logged as error message.
  195. * @private
  196. *
  197. * @param {String} errorMessage The event containing the error
  198. */
  199. _onError: function ( errorMessage ) {
  200. if ( this.logging.enabled && this.logging.debug ) {
  201. console.error( errorMessage );
  202. }
  203. },
  204. _onAssetAvailable: function ( /*payload*/ ) {
  205. const errorMessage = 'OBJLoader2Parser does not provide implementation for onAssetAvailable. Aborting...';
  206. this.callbacks.onError( errorMessage );
  207. throw errorMessage;
  208. },
  209. _onLoad: function ( object3d, message ) {
  210. console.log( 'You reached parser default onLoad callback: ' + message );
  211. },
  212. /**
  213. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  214. *
  215. * @param {boolean} enabled True or false.
  216. * @param {boolean} debug True or false.
  217. *
  218. * @return {OBJLoader2Parser}
  219. */
  220. setLogging: function ( enabled, debug ) {
  221. this.logging.enabled = enabled === true;
  222. this.logging.debug = debug === true;
  223. return this;
  224. },
  225. _configure: function () {
  226. this._pushSmoothingGroup( 1 );
  227. if ( this.logging.enabled ) {
  228. const matKeys = Object.keys( this.materials );
  229. const matNames = ( matKeys.length > 0 ) ? '\n\tmaterialNames:\n\t\t- ' + matKeys.join( '\n\t\t- ' ) : '\n\tmaterialNames: None';
  230. let printedConfig = 'OBJLoader.Parser configuration:'
  231. + matNames
  232. + '\n\tmaterialPerSmoothingGroup: ' + this.materialPerSmoothingGroup
  233. + '\n\tuseOAsMesh: ' + this.useOAsMesh
  234. + '\n\tuseIndices: ' + this.useIndices
  235. + '\n\tdisregardNormals: ' + this.disregardNormals;
  236. printedConfig += '\n\tcallbacks.onProgress: ' + this.callbacks.onProgress.name;
  237. printedConfig += '\n\tcallbacks.onAssetAvailable: ' + this.callbacks.onAssetAvailable.name;
  238. printedConfig += '\n\tcallbacks.onError: ' + this.callbacks.onError.name;
  239. console.info( printedConfig );
  240. }
  241. },
  242. /**
  243. * Parse the provided arraybuffer
  244. *
  245. * @param {Uint8Array} arrayBuffer OBJ data as Uint8Array
  246. */
  247. execute: function ( arrayBuffer ) {
  248. if ( this.logging.enabled ) console.time( 'OBJLoader2Parser.execute' );
  249. this._configure();
  250. const arrayBufferView = new Uint8Array( arrayBuffer );
  251. this.contentRef = arrayBufferView;
  252. const length = arrayBufferView.byteLength;
  253. this.globalCounts.totalBytes = length;
  254. const buffer = new Array( 128 );
  255. let bufferPointer = 0;
  256. let slashesCount = 0;
  257. let word = '';
  258. let currentByte = 0;
  259. for ( let code; currentByte < length; currentByte ++ ) {
  260. code = arrayBufferView[ currentByte ];
  261. switch ( code ) {
  262. // space
  263. case 32:
  264. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  265. word = '';
  266. break;
  267. // slash
  268. case 47:
  269. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  270. slashesCount ++;
  271. word = '';
  272. break;
  273. // LF
  274. case 10:
  275. this._processLine( buffer, bufferPointer, slashesCount, word, currentByte );
  276. word = '';
  277. bufferPointer = 0;
  278. slashesCount = 0;
  279. break;
  280. // CR
  281. case 13:
  282. break;
  283. default:
  284. word += String.fromCharCode( code );
  285. break;
  286. }
  287. }
  288. this._processLine( buffer, bufferPointer, slashesCount, word, currentByte );
  289. this._finalizeParsing();
  290. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2Parser.execute' );
  291. },
  292. /**
  293. * Parse the provided text
  294. *
  295. * @param {string} text OBJ data as string
  296. */
  297. executeLegacy: function ( text ) {
  298. if ( this.logging.enabled ) console.time( 'OBJLoader2Parser.executeLegacy' );
  299. this._configure();
  300. this.legacyMode = true;
  301. this.contentRef = text;
  302. const length = text.length;
  303. this.globalCounts.totalBytes = length;
  304. const buffer = new Array( 128 );
  305. let bufferPointer = 0;
  306. let slashesCount = 0;
  307. let word = '';
  308. let currentByte = 0;
  309. for ( let char; currentByte < length; currentByte ++ ) {
  310. char = text[ currentByte ];
  311. switch ( char ) {
  312. case ' ':
  313. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  314. word = '';
  315. break;
  316. case '/':
  317. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  318. slashesCount ++;
  319. word = '';
  320. break;
  321. case '\n':
  322. this._processLine( buffer, bufferPointer, slashesCount, word, currentByte );
  323. word = '';
  324. bufferPointer = 0;
  325. slashesCount = 0;
  326. break;
  327. case '\r':
  328. break;
  329. default:
  330. word += char;
  331. }
  332. }
  333. this._processLine( buffer, bufferPointer, word, slashesCount );
  334. this._finalizeParsing();
  335. if ( this.logging.enabled ) console.timeEnd( 'OBJLoader2Parser.executeLegacy' );
  336. },
  337. _processLine: function ( buffer, bufferPointer, slashesCount, word, currentByte ) {
  338. this.globalCounts.lineByte = this.globalCounts.currentByte;
  339. this.globalCounts.currentByte = currentByte;
  340. if ( bufferPointer < 1 ) return;
  341. if ( word.length > 0 ) buffer[ bufferPointer ++ ] = word;
  342. const reconstructString = function ( content, legacyMode, start, stop ) {
  343. let line = '';
  344. if ( stop > start ) {
  345. let i;
  346. if ( legacyMode ) {
  347. for ( i = start; i < stop; i ++ ) line += content[ i ];
  348. } else {
  349. for ( i = start; i < stop; i ++ ) line += String.fromCharCode( content[ i ] );
  350. }
  351. line = line.trim();
  352. }
  353. return line;
  354. };
  355. let bufferLength, length, i;
  356. const lineDesignation = buffer[ 0 ];
  357. switch ( lineDesignation ) {
  358. case 'v':
  359. this.vertices.push( parseFloat( buffer[ 1 ] ) );
  360. this.vertices.push( parseFloat( buffer[ 2 ] ) );
  361. this.vertices.push( parseFloat( buffer[ 3 ] ) );
  362. if ( bufferPointer > 4 ) {
  363. this.colors.push( parseFloat( buffer[ 4 ] ) );
  364. this.colors.push( parseFloat( buffer[ 5 ] ) );
  365. this.colors.push( parseFloat( buffer[ 6 ] ) );
  366. }
  367. break;
  368. case 'vt':
  369. this.uvs.push( parseFloat( buffer[ 1 ] ) );
  370. this.uvs.push( parseFloat( buffer[ 2 ] ) );
  371. break;
  372. case 'vn':
  373. this.normals.push( parseFloat( buffer[ 1 ] ) );
  374. this.normals.push( parseFloat( buffer[ 2 ] ) );
  375. this.normals.push( parseFloat( buffer[ 3 ] ) );
  376. break;
  377. case 'f':
  378. bufferLength = bufferPointer - 1;
  379. // "f vertex ..."
  380. if ( slashesCount === 0 ) {
  381. this._checkFaceType( 0 );
  382. for ( i = 2, length = bufferLength; i < length; i ++ ) {
  383. this._buildFace( buffer[ 1 ] );
  384. this._buildFace( buffer[ i ] );
  385. this._buildFace( buffer[ i + 1 ] );
  386. }
  387. // "f vertex/uv ..."
  388. } else if ( bufferLength === slashesCount * 2 ) {
  389. this._checkFaceType( 1 );
  390. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  391. this._buildFace( buffer[ 1 ], buffer[ 2 ] );
  392. this._buildFace( buffer[ i ], buffer[ i + 1 ] );
  393. this._buildFace( buffer[ i + 2 ], buffer[ i + 3 ] );
  394. }
  395. // "f vertex/uv/normal ..."
  396. } else if ( bufferLength * 2 === slashesCount * 3 ) {
  397. this._checkFaceType( 2 );
  398. for ( i = 4, length = bufferLength - 3; i < length; i += 3 ) {
  399. this._buildFace( buffer[ 1 ], buffer[ 2 ], buffer[ 3 ] );
  400. this._buildFace( buffer[ i ], buffer[ i + 1 ], buffer[ i + 2 ] );
  401. this._buildFace( buffer[ i + 3 ], buffer[ i + 4 ], buffer[ i + 5 ] );
  402. }
  403. // "f vertex//normal ..."
  404. } else {
  405. this._checkFaceType( 3 );
  406. for ( i = 3, length = bufferLength - 2; i < length; i += 2 ) {
  407. this._buildFace( buffer[ 1 ], undefined, buffer[ 2 ] );
  408. this._buildFace( buffer[ i ], undefined, buffer[ i + 1 ] );
  409. this._buildFace( buffer[ i + 2 ], undefined, buffer[ i + 3 ] );
  410. }
  411. }
  412. break;
  413. case 'l':
  414. case 'p':
  415. bufferLength = bufferPointer - 1;
  416. if ( bufferLength === slashesCount * 2 ) {
  417. this._checkFaceType( 4 );
  418. for ( i = 1, length = bufferLength + 1; i < length; i += 2 ) this._buildFace( buffer[ i ], buffer[ i + 1 ] );
  419. } else {
  420. this._checkFaceType( ( lineDesignation === 'l' ) ? 5 : 6 );
  421. for ( i = 1, length = bufferLength + 1; i < length; i ++ ) this._buildFace( buffer[ i ] );
  422. }
  423. break;
  424. case 's':
  425. this._pushSmoothingGroup( buffer[ 1 ] );
  426. break;
  427. case 'g':
  428. // 'g' leads to creation of mesh if valid data (faces declaration was done before), otherwise only groupName gets set
  429. this._processCompletedMesh();
  430. this.rawMesh.groupName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  431. break;
  432. case 'o':
  433. // 'o' is meta-information and usually does not result in creation of new meshes, but can be enforced with "useOAsMesh"
  434. if ( this.useOAsMesh ) this._processCompletedMesh();
  435. this.rawMesh.objectName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 2, this.globalCounts.currentByte );
  436. break;
  437. case 'mtllib':
  438. this.rawMesh.mtllibName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  439. break;
  440. case 'usemtl':
  441. const mtlName = reconstructString( this.contentRef, this.legacyMode, this.globalCounts.lineByte + 7, this.globalCounts.currentByte );
  442. if ( mtlName !== '' && this.rawMesh.activeMtlName !== mtlName ) {
  443. this.rawMesh.activeMtlName = mtlName;
  444. this.rawMesh.counts.mtlCount ++;
  445. this._checkSubGroup();
  446. }
  447. break;
  448. default:
  449. break;
  450. }
  451. },
  452. _pushSmoothingGroup: function ( smoothingGroup ) {
  453. let smoothingGroupInt = parseInt( smoothingGroup );
  454. if ( isNaN( smoothingGroupInt ) ) {
  455. smoothingGroupInt = smoothingGroup === 'off' ? 0 : 1;
  456. }
  457. const smoothCheck = this.rawMesh.smoothingGroup.normalized;
  458. this.rawMesh.smoothingGroup.normalized = this.rawMesh.smoothingGroup.splitMaterials ? smoothingGroupInt : ( smoothingGroupInt === 0 ) ? 0 : 1;
  459. this.rawMesh.smoothingGroup.real = smoothingGroupInt;
  460. if ( smoothCheck !== smoothingGroupInt ) {
  461. this.rawMesh.counts.smoothingGroupCount ++;
  462. this._checkSubGroup();
  463. }
  464. },
  465. /**
  466. * Expanded faceTypes include all four face types, both line types and the point type
  467. * faceType = 0: "f vertex ..."
  468. * faceType = 1: "f vertex/uv ..."
  469. * faceType = 2: "f vertex/uv/normal ..."
  470. * faceType = 3: "f vertex//normal ..."
  471. * faceType = 4: "l vertex/uv ..." or "l vertex ..."
  472. * faceType = 5: "l vertex ..."
  473. * faceType = 6: "p vertex ..."
  474. */
  475. _checkFaceType: function ( faceType ) {
  476. if ( this.rawMesh.faceType !== faceType ) {
  477. this._processCompletedMesh();
  478. this.rawMesh.faceType = faceType;
  479. this._checkSubGroup();
  480. }
  481. },
  482. _checkSubGroup: function () {
  483. const index = this.rawMesh.activeMtlName + '|' + this.rawMesh.smoothingGroup.normalized;
  484. this.rawMesh.subGroupInUse = this.rawMesh.subGroups[ index ];
  485. if ( this.rawMesh.subGroupInUse === undefined || this.rawMesh.subGroupInUse === null ) {
  486. this.rawMesh.subGroupInUse = {
  487. index: index,
  488. objectName: this.rawMesh.objectName,
  489. groupName: this.rawMesh.groupName,
  490. materialName: this.rawMesh.activeMtlName,
  491. smoothingGroup: this.rawMesh.smoothingGroup.normalized,
  492. vertices: [],
  493. indexMappingsCount: 0,
  494. indexMappings: [],
  495. indices: [],
  496. colors: [],
  497. uvs: [],
  498. normals: []
  499. };
  500. this.rawMesh.subGroups[ index ] = this.rawMesh.subGroupInUse;
  501. }
  502. },
  503. _buildFace: function ( faceIndexV, faceIndexU, faceIndexN ) {
  504. const subGroupInUse = this.rawMesh.subGroupInUse;
  505. const scope = this;
  506. const updateSubGroupInUse = function () {
  507. const faceIndexVi = parseInt( faceIndexV );
  508. let indexPointerV = 3 * ( faceIndexVi > 0 ? faceIndexVi - 1 : faceIndexVi + scope.vertices.length / 3 );
  509. let indexPointerC = scope.colors.length > 0 ? indexPointerV : null;
  510. const vertices = subGroupInUse.vertices;
  511. vertices.push( scope.vertices[ indexPointerV ++ ] );
  512. vertices.push( scope.vertices[ indexPointerV ++ ] );
  513. vertices.push( scope.vertices[ indexPointerV ] );
  514. if ( indexPointerC !== null ) {
  515. const colors = subGroupInUse.colors;
  516. colors.push( scope.colors[ indexPointerC ++ ] );
  517. colors.push( scope.colors[ indexPointerC ++ ] );
  518. colors.push( scope.colors[ indexPointerC ] );
  519. }
  520. if ( faceIndexU ) {
  521. const faceIndexUi = parseInt( faceIndexU );
  522. let indexPointerU = 2 * ( faceIndexUi > 0 ? faceIndexUi - 1 : faceIndexUi + scope.uvs.length / 2 );
  523. const uvs = subGroupInUse.uvs;
  524. uvs.push( scope.uvs[ indexPointerU ++ ] );
  525. uvs.push( scope.uvs[ indexPointerU ] );
  526. }
  527. if ( faceIndexN && ! scope.disregardNormals ) {
  528. const faceIndexNi = parseInt( faceIndexN );
  529. let indexPointerN = 3 * ( faceIndexNi > 0 ? faceIndexNi - 1 : faceIndexNi + scope.normals.length / 3 );
  530. const normals = subGroupInUse.normals;
  531. normals.push( scope.normals[ indexPointerN ++ ] );
  532. normals.push( scope.normals[ indexPointerN ++ ] );
  533. normals.push( scope.normals[ indexPointerN ] );
  534. }
  535. };
  536. if ( this.useIndices ) {
  537. if ( this.disregardNormals ) faceIndexN = undefined;
  538. const mappingName = faceIndexV + ( faceIndexU ? '_' + faceIndexU : '_n' ) + ( faceIndexN ? '_' + faceIndexN : '_n' );
  539. let indicesPointer = subGroupInUse.indexMappings[ mappingName ];
  540. if ( indicesPointer === undefined || indicesPointer === null ) {
  541. indicesPointer = this.rawMesh.subGroupInUse.vertices.length / 3;
  542. updateSubGroupInUse();
  543. subGroupInUse.indexMappings[ mappingName ] = indicesPointer;
  544. subGroupInUse.indexMappingsCount ++;
  545. } else {
  546. this.rawMesh.counts.doubleIndicesCount ++;
  547. }
  548. subGroupInUse.indices.push( indicesPointer );
  549. } else {
  550. updateSubGroupInUse();
  551. }
  552. this.rawMesh.counts.faceCount ++;
  553. },
  554. _createRawMeshReport: function ( inputObjectCount ) {
  555. return 'Input Object number: ' + inputObjectCount +
  556. '\n\tObject name: ' + this.rawMesh.objectName +
  557. '\n\tGroup name: ' + this.rawMesh.groupName +
  558. '\n\tMtllib name: ' + this.rawMesh.mtllibName +
  559. '\n\tVertex count: ' + this.vertices.length / 3 +
  560. '\n\tNormal count: ' + this.normals.length / 3 +
  561. '\n\tUV count: ' + this.uvs.length / 2 +
  562. '\n\tSmoothingGroup count: ' + this.rawMesh.counts.smoothingGroupCount +
  563. '\n\tMaterial count: ' + this.rawMesh.counts.mtlCount +
  564. '\n\tReal MeshOutputGroup count: ' + this.rawMesh.subGroups.length;
  565. },
  566. /**
  567. * Clear any empty subGroup and calculate absolute vertex, normal and uv counts
  568. */
  569. _finalizeRawMesh: function () {
  570. const meshOutputGroupTemp = [];
  571. let meshOutputGroup;
  572. let absoluteVertexCount = 0;
  573. let absoluteIndexMappingsCount = 0;
  574. let absoluteIndexCount = 0;
  575. let absoluteColorCount = 0;
  576. let absoluteNormalCount = 0;
  577. let absoluteUvCount = 0;
  578. let indices;
  579. for ( const name in this.rawMesh.subGroups ) {
  580. meshOutputGroup = this.rawMesh.subGroups[ name ];
  581. if ( meshOutputGroup.vertices.length > 0 ) {
  582. indices = meshOutputGroup.indices;
  583. if ( indices.length > 0 && absoluteIndexMappingsCount > 0 ) {
  584. for ( let i = 0; i < indices.length; i ++ ) {
  585. indices[ i ] = indices[ i ] + absoluteIndexMappingsCount;
  586. }
  587. }
  588. meshOutputGroupTemp.push( meshOutputGroup );
  589. absoluteVertexCount += meshOutputGroup.vertices.length;
  590. absoluteIndexMappingsCount += meshOutputGroup.indexMappingsCount;
  591. absoluteIndexCount += meshOutputGroup.indices.length;
  592. absoluteColorCount += meshOutputGroup.colors.length;
  593. absoluteUvCount += meshOutputGroup.uvs.length;
  594. absoluteNormalCount += meshOutputGroup.normals.length;
  595. }
  596. }
  597. // do not continue if no result
  598. let result = null;
  599. if ( meshOutputGroupTemp.length > 0 ) {
  600. result = {
  601. name: this.rawMesh.groupName !== '' ? this.rawMesh.groupName : this.rawMesh.objectName,
  602. subGroups: meshOutputGroupTemp,
  603. absoluteVertexCount: absoluteVertexCount,
  604. absoluteIndexCount: absoluteIndexCount,
  605. absoluteColorCount: absoluteColorCount,
  606. absoluteNormalCount: absoluteNormalCount,
  607. absoluteUvCount: absoluteUvCount,
  608. faceCount: this.rawMesh.counts.faceCount,
  609. doubleIndicesCount: this.rawMesh.counts.doubleIndicesCount
  610. };
  611. }
  612. return result;
  613. },
  614. _processCompletedMesh: function () {
  615. const result = this._finalizeRawMesh();
  616. const haveMesh = result !== null;
  617. if ( haveMesh ) {
  618. if ( this.colors.length > 0 && this.colors.length !== this.vertices.length ) {
  619. this.callbacks.onError( 'Vertex Colors were detected, but vertex count and color count do not match!' );
  620. }
  621. if ( this.logging.enabled && this.logging.debug ) console.debug( this._createRawMeshReport( this.inputObjectCount ) );
  622. this.inputObjectCount ++;
  623. this._buildMesh( result );
  624. const progressBytesPercent = this.globalCounts.currentByte / this.globalCounts.totalBytes;
  625. this._onProgress( 'Completed [o: ' + this.rawMesh.objectName + ' g:' + this.rawMesh.groupName + '' +
  626. '] Total progress: ' + ( progressBytesPercent * 100 ).toFixed( 2 ) + '%' );
  627. this._resetRawMesh();
  628. }
  629. return haveMesh;
  630. },
  631. /**
  632. * SubGroups are transformed to too intermediate format that is forwarded to the MeshReceiver.
  633. * It is ensured that SubGroups only contain objects with vertices (no need to check).
  634. *
  635. * @param result
  636. */
  637. _buildMesh: function ( result ) {
  638. const meshOutputGroups = result.subGroups;
  639. const vertexFA = new Float32Array( result.absoluteVertexCount );
  640. this.globalCounts.vertices += result.absoluteVertexCount / 3;
  641. this.globalCounts.faces += result.faceCount;
  642. this.globalCounts.doubleIndicesCount += result.doubleIndicesCount;
  643. const indexUA = ( result.absoluteIndexCount > 0 ) ? new Uint32Array( result.absoluteIndexCount ) : null;
  644. const colorFA = ( result.absoluteColorCount > 0 ) ? new Float32Array( result.absoluteColorCount ) : null;
  645. const normalFA = ( result.absoluteNormalCount > 0 ) ? new Float32Array( result.absoluteNormalCount ) : null;
  646. const uvFA = ( result.absoluteUvCount > 0 ) ? new Float32Array( result.absoluteUvCount ) : null;
  647. const haveVertexColors = colorFA !== null;
  648. let meshOutputGroup;
  649. const materialNames = [];
  650. const createMultiMaterial = ( meshOutputGroups.length > 1 );
  651. let materialIndex = 0;
  652. const materialIndexMapping = [];
  653. let selectedMaterialIndex;
  654. let materialGroup;
  655. const materialGroups = [];
  656. let vertexFAOffset = 0;
  657. let indexUAOffset = 0;
  658. let colorFAOffset = 0;
  659. let normalFAOffset = 0;
  660. let uvFAOffset = 0;
  661. let materialGroupOffset = 0;
  662. let materialGroupLength = 0;
  663. let materialOrg, material, materialName, materialNameOrg;
  664. // only one specific face type
  665. for ( const oodIndex in meshOutputGroups ) {
  666. if ( ! meshOutputGroups.hasOwnProperty( oodIndex ) ) continue;
  667. meshOutputGroup = meshOutputGroups[ oodIndex ];
  668. materialNameOrg = meshOutputGroup.materialName;
  669. if ( this.rawMesh.faceType < 4 ) {
  670. materialName = materialNameOrg + ( haveVertexColors ? '_vertexColor' : '' ) + ( meshOutputGroup.smoothingGroup === 0 ? '_flat' : '' );
  671. } else {
  672. materialName = this.rawMesh.faceType === 6 ? 'defaultPointMaterial' : 'defaultLineMaterial';
  673. }
  674. materialOrg = this.materials[ materialNameOrg ];
  675. material = this.materials[ materialName ];
  676. // both original and derived names do not lead to an existing material => need to use a default material
  677. if ( ( materialOrg === undefined || materialOrg === null ) && ( material === undefined || material === null ) ) {
  678. materialName = haveVertexColors ? 'defaultVertexColorMaterial' : 'defaultMaterial';
  679. material = this.materials[ materialName ];
  680. if ( this.logging.enabled ) {
  681. console.info( 'object_group "' + meshOutputGroup.objectName + '_' +
  682. meshOutputGroup.groupName + '" was defined with unresolvable material "' +
  683. materialNameOrg + '"! Assigning "' + materialName + '".' );
  684. }
  685. }
  686. if ( material === undefined || material === null ) {
  687. const materialCloneInstructions = {
  688. materialNameOrg: materialNameOrg,
  689. materialName: materialName,
  690. materialProperties: {
  691. vertexColors: haveVertexColors ? 2 : 0,
  692. flatShading: meshOutputGroup.smoothingGroup === 0
  693. }
  694. };
  695. const payload = {
  696. cmd: 'assetAvailable',
  697. type: 'material',
  698. materials: {
  699. materialCloneInstructions: materialCloneInstructions
  700. }
  701. };
  702. this.callbacks.onAssetAvailable( payload );
  703. // only set materials if they don't exist, yet
  704. const matCheck = this.materials[ materialName ];
  705. if ( matCheck === undefined || matCheck === null ) {
  706. this.materials[ materialName ] = materialCloneInstructions;
  707. }
  708. }
  709. if ( createMultiMaterial ) {
  710. // re-use material if already used before. Reduces materials array size and eliminates duplicates
  711. selectedMaterialIndex = materialIndexMapping[ materialName ];
  712. if ( ! selectedMaterialIndex ) {
  713. selectedMaterialIndex = materialIndex;
  714. materialIndexMapping[ materialName ] = materialIndex;
  715. materialNames.push( materialName );
  716. materialIndex ++;
  717. }
  718. materialGroupLength = this.useIndices ? meshOutputGroup.indices.length : meshOutputGroup.vertices.length / 3;
  719. materialGroup = {
  720. start: materialGroupOffset,
  721. count: materialGroupLength,
  722. index: selectedMaterialIndex
  723. };
  724. materialGroups.push( materialGroup );
  725. materialGroupOffset += materialGroupLength;
  726. } else {
  727. materialNames.push( materialName );
  728. }
  729. vertexFA.set( meshOutputGroup.vertices, vertexFAOffset );
  730. vertexFAOffset += meshOutputGroup.vertices.length;
  731. if ( indexUA ) {
  732. indexUA.set( meshOutputGroup.indices, indexUAOffset );
  733. indexUAOffset += meshOutputGroup.indices.length;
  734. }
  735. if ( colorFA ) {
  736. colorFA.set( meshOutputGroup.colors, colorFAOffset );
  737. colorFAOffset += meshOutputGroup.colors.length;
  738. }
  739. if ( normalFA ) {
  740. normalFA.set( meshOutputGroup.normals, normalFAOffset );
  741. normalFAOffset += meshOutputGroup.normals.length;
  742. }
  743. if ( uvFA ) {
  744. uvFA.set( meshOutputGroup.uvs, uvFAOffset );
  745. uvFAOffset += meshOutputGroup.uvs.length;
  746. }
  747. if ( this.logging.enabled && this.logging.debug ) {
  748. let materialIndexLine = '';
  749. if ( selectedMaterialIndex ) {
  750. materialIndexLine = '\n\t\tmaterialIndex: ' + selectedMaterialIndex;
  751. }
  752. const createdReport = '\tOutput Object no.: ' + this.outputObjectCount +
  753. '\n\t\tgroupName: ' + meshOutputGroup.groupName +
  754. '\n\t\tIndex: ' + meshOutputGroup.index +
  755. '\n\t\tfaceType: ' + this.rawMesh.faceType +
  756. '\n\t\tmaterialName: ' + meshOutputGroup.materialName +
  757. '\n\t\tsmoothingGroup: ' + meshOutputGroup.smoothingGroup +
  758. materialIndexLine +
  759. '\n\t\tobjectName: ' + meshOutputGroup.objectName +
  760. '\n\t\t#vertices: ' + meshOutputGroup.vertices.length / 3 +
  761. '\n\t\t#indices: ' + meshOutputGroup.indices.length +
  762. '\n\t\t#colors: ' + meshOutputGroup.colors.length / 3 +
  763. '\n\t\t#uvs: ' + meshOutputGroup.uvs.length / 2 +
  764. '\n\t\t#normals: ' + meshOutputGroup.normals.length / 3;
  765. console.debug( createdReport );
  766. }
  767. }
  768. this.outputObjectCount ++;
  769. this.callbacks.onAssetAvailable(
  770. {
  771. cmd: 'assetAvailable',
  772. type: 'mesh',
  773. progress: {
  774. numericalValue: this.globalCounts.currentByte / this.globalCounts.totalBytes
  775. },
  776. params: {
  777. meshName: result.name
  778. },
  779. materials: {
  780. multiMaterial: createMultiMaterial,
  781. materialNames: materialNames,
  782. materialGroups: materialGroups
  783. },
  784. buffers: {
  785. vertices: vertexFA,
  786. indices: indexUA,
  787. colors: colorFA,
  788. normals: normalFA,
  789. uvs: uvFA
  790. },
  791. // 0: mesh, 1: line, 2: point
  792. geometryType: this.rawMesh.faceType < 4 ? 0 : ( this.rawMesh.faceType === 6 ) ? 2 : 1
  793. },
  794. [ vertexFA.buffer ],
  795. indexUA !== null ? [ indexUA.buffer ] : null,
  796. colorFA !== null ? [ colorFA.buffer ] : null,
  797. normalFA !== null ? [ normalFA.buffer ] : null,
  798. uvFA !== null ? [ uvFA.buffer ] : null
  799. );
  800. },
  801. _finalizeParsing: function () {
  802. if ( this.logging.enabled ) console.info( 'Global output object count: ' + this.outputObjectCount );
  803. if ( this._processCompletedMesh() && this.logging.enabled ) {
  804. const parserFinalReport = 'Overall counts: ' +
  805. '\n\tVertices: ' + this.globalCounts.vertices +
  806. '\n\tFaces: ' + this.globalCounts.faces +
  807. '\n\tMultiple definitions: ' + this.globalCounts.doubleIndicesCount;
  808. console.info( parserFinalReport );
  809. }
  810. }
  811. };
  812. export { OBJLoader2Parser };