LWOLoader.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. ( function () {
  2. /**
  3. * @version 1.1.1
  4. *
  5. * @desc Load files in LWO3 and LWO2 format on Three.js
  6. *
  7. * LWO3 format specification:
  8. * https://static.lightwave3d.com/sdk/2019/html/filefmts/lwo3.html
  9. *
  10. * LWO2 format specification:
  11. * https://static.lightwave3d.com/sdk/2019/html/filefmts/lwo2.html
  12. *
  13. **/
  14. let _lwoTree;
  15. class LWOLoader extends THREE.Loader {
  16. constructor( manager, parameters = {} ) {
  17. super( manager );
  18. this.resourcePath = parameters.resourcePath !== undefined ? parameters.resourcePath : '';
  19. }
  20. load( url, onLoad, onProgress, onError ) {
  21. const scope = this;
  22. const path = scope.path === '' ? extractParentUrl( url, 'Objects' ) : scope.path;
  23. // give the mesh a default name based on the filename
  24. const modelName = url.split( path ).pop().split( '.' )[ 0 ];
  25. const loader = new THREE.FileLoader( this.manager );
  26. loader.setPath( scope.path );
  27. loader.setResponseType( 'arraybuffer' );
  28. loader.load( url, function ( buffer ) {
  29. // console.time( 'Total parsing: ' );
  30. try {
  31. onLoad( scope.parse( buffer, path, modelName ) );
  32. } catch ( e ) {
  33. if ( onError ) {
  34. onError( e );
  35. } else {
  36. console.error( e );
  37. }
  38. scope.manager.itemError( url );
  39. }
  40. // console.timeEnd( 'Total parsing: ' );
  41. }, onProgress, onError );
  42. }
  43. parse( iffBuffer, path, modelName ) {
  44. _lwoTree = new THREE.IFFParser().parse( iffBuffer );
  45. // console.log( 'lwoTree', lwoTree );
  46. const textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  47. return new LWOTreeParser( textureLoader ).parse( modelName );
  48. }
  49. }
  50. // Parse the lwoTree object
  51. class LWOTreeParser {
  52. constructor( textureLoader ) {
  53. this.textureLoader = textureLoader;
  54. }
  55. parse( modelName ) {
  56. this.materials = new MaterialParser( this.textureLoader ).parse();
  57. this.defaultLayerName = modelName;
  58. this.meshes = this.parseLayers();
  59. return {
  60. materials: this.materials,
  61. meshes: this.meshes
  62. };
  63. }
  64. parseLayers() {
  65. // array of all meshes for building hierarchy
  66. const meshes = [];
  67. // final array containing meshes with scene graph hierarchy set up
  68. const finalMeshes = [];
  69. const geometryParser = new GeometryParser();
  70. const scope = this;
  71. _lwoTree.layers.forEach( function ( layer ) {
  72. const geometry = geometryParser.parse( layer.geometry, layer );
  73. const mesh = scope.parseMesh( geometry, layer );
  74. meshes[ layer.number ] = mesh;
  75. if ( layer.parent === - 1 ) finalMeshes.push( mesh ); else meshes[ layer.parent ].add( mesh );
  76. } );
  77. this.applyPivots( finalMeshes );
  78. return finalMeshes;
  79. }
  80. parseMesh( geometry, layer ) {
  81. let mesh;
  82. const materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  83. this.duplicateUVs( geometry, materials );
  84. if ( layer.geometry.type === 'points' ) mesh = new THREE.Points( geometry, materials ); else if ( layer.geometry.type === 'lines' ) mesh = new THREE.LineSegments( geometry, materials ); else mesh = new THREE.Mesh( geometry, materials );
  85. if ( layer.name ) mesh.name = layer.name; else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  86. mesh.userData.pivot = layer.pivot;
  87. return mesh;
  88. }
  89. // TODO: may need to be reversed in z to convert LWO to three.js coordinates
  90. applyPivots( meshes ) {
  91. meshes.forEach( function ( mesh ) {
  92. mesh.traverse( function ( child ) {
  93. const pivot = child.userData.pivot;
  94. child.position.x += pivot[ 0 ];
  95. child.position.y += pivot[ 1 ];
  96. child.position.z += pivot[ 2 ];
  97. if ( child.parent ) {
  98. const parentPivot = child.parent.userData.pivot;
  99. child.position.x -= parentPivot[ 0 ];
  100. child.position.y -= parentPivot[ 1 ];
  101. child.position.z -= parentPivot[ 2 ];
  102. }
  103. } );
  104. } );
  105. }
  106. getMaterials( namesArray, type ) {
  107. const materials = [];
  108. const scope = this;
  109. namesArray.forEach( function ( name, i ) {
  110. materials[ i ] = scope.getMaterialByName( name );
  111. } );
  112. // convert materials to line or point mats if required
  113. if ( type === 'points' || type === 'lines' ) {
  114. materials.forEach( function ( mat, i ) {
  115. const spec = {
  116. color: mat.color
  117. };
  118. if ( type === 'points' ) {
  119. spec.size = 0.1;
  120. spec.map = mat.map;
  121. materials[ i ] = new THREE.PointsMaterial( spec );
  122. } else if ( type === 'lines' ) {
  123. materials[ i ] = new THREE.LineBasicMaterial( spec );
  124. }
  125. } );
  126. }
  127. // if there is only one material, return that directly instead of array
  128. const filtered = materials.filter( Boolean );
  129. if ( filtered.length === 1 ) return filtered[ 0 ];
  130. return materials;
  131. }
  132. getMaterialByName( name ) {
  133. return this.materials.filter( function ( m ) {
  134. return m.name === name;
  135. } )[ 0 ];
  136. }
  137. // If the material has an aoMap, duplicate UVs
  138. duplicateUVs( geometry, materials ) {
  139. let duplicateUVs = false;
  140. if ( ! Array.isArray( materials ) ) {
  141. if ( materials.aoMap ) duplicateUVs = true;
  142. } else {
  143. materials.forEach( function ( material ) {
  144. if ( material.aoMap ) duplicateUVs = true;
  145. } );
  146. }
  147. if ( ! duplicateUVs ) return;
  148. geometry.setAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  149. }
  150. }
  151. class MaterialParser {
  152. constructor( textureLoader ) {
  153. this.textureLoader = textureLoader;
  154. }
  155. parse() {
  156. const materials = [];
  157. this.textures = {};
  158. for ( const name in _lwoTree.materials ) {
  159. if ( _lwoTree.format === 'LWO3' ) {
  160. materials.push( this.parseMaterial( _lwoTree.materials[ name ], name, _lwoTree.textures ) );
  161. } else if ( _lwoTree.format === 'LWO2' ) {
  162. materials.push( this.parseMaterialLwo2( _lwoTree.materials[ name ], name, _lwoTree.textures ) );
  163. }
  164. }
  165. return materials;
  166. }
  167. parseMaterial( materialData, name, textures ) {
  168. let params = {
  169. name: name,
  170. side: this.getSide( materialData.attributes ),
  171. flatShading: this.getSmooth( materialData.attributes )
  172. };
  173. const connections = this.parseConnections( materialData.connections, materialData.nodes );
  174. const maps = this.parseTextureNodes( connections.maps );
  175. this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );
  176. const attributes = this.parseAttributes( connections.attributes, maps );
  177. this.parseEnvMap( connections, maps, attributes );
  178. params = Object.assign( maps, params );
  179. params = Object.assign( params, attributes );
  180. const materialType = this.getMaterialType( connections.attributes );
  181. if ( materialType !== THREE.MeshPhongMaterial ) delete params.refractionRatio; // PBR materials do not support "refractionRatio"
  182. return new materialType( params );
  183. }
  184. parseMaterialLwo2( materialData, name /*, textures*/ ) {
  185. let params = {
  186. name: name,
  187. side: this.getSide( materialData.attributes ),
  188. flatShading: this.getSmooth( materialData.attributes )
  189. };
  190. const attributes = this.parseAttributes( materialData.attributes, {} );
  191. params = Object.assign( params, attributes );
  192. return new THREE.MeshPhongMaterial( params );
  193. }
  194. // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  195. // then switching mat THREE.FrontSide -> THREE.BackSide
  196. // NB: this means that THREE.FrontSide and THREE.BackSide have been switched!
  197. getSide( attributes ) {
  198. if ( ! attributes.side ) return THREE.BackSide;
  199. switch ( attributes.side ) {
  200. case 0:
  201. case 1:
  202. return THREE.BackSide;
  203. case 2:
  204. return THREE.FrontSide;
  205. case 3:
  206. return THREE.DoubleSide;
  207. }
  208. }
  209. getSmooth( attributes ) {
  210. if ( ! attributes.smooth ) return true;
  211. return ! attributes.smooth;
  212. }
  213. parseConnections( connections, nodes ) {
  214. const materialConnections = {
  215. maps: {}
  216. };
  217. const inputName = connections.inputName;
  218. const inputNodeName = connections.inputNodeName;
  219. const nodeName = connections.nodeName;
  220. const scope = this;
  221. inputName.forEach( function ( name, index ) {
  222. if ( name === 'Material' ) {
  223. const matNode = scope.getNodeByRefName( inputNodeName[ index ], nodes );
  224. materialConnections.attributes = matNode.attributes;
  225. materialConnections.envMap = matNode.fileName;
  226. materialConnections.name = inputNodeName[ index ];
  227. }
  228. } );
  229. nodeName.forEach( function ( name, index ) {
  230. if ( name === materialConnections.name ) {
  231. materialConnections.maps[ inputName[ index ] ] = scope.getNodeByRefName( inputNodeName[ index ], nodes );
  232. }
  233. } );
  234. return materialConnections;
  235. }
  236. getNodeByRefName( refName, nodes ) {
  237. for ( const name in nodes ) {
  238. if ( nodes[ name ].refName === refName ) return nodes[ name ];
  239. }
  240. }
  241. parseTextureNodes( textureNodes ) {
  242. const maps = {};
  243. for ( const name in textureNodes ) {
  244. const node = textureNodes[ name ];
  245. const path = node.fileName;
  246. if ( ! path ) return;
  247. const texture = this.loadTexture( path );
  248. if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
  249. if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );
  250. switch ( name ) {
  251. case 'Color':
  252. maps.map = texture;
  253. break;
  254. case 'Roughness':
  255. maps.roughnessMap = texture;
  256. maps.roughness = 1;
  257. break;
  258. case 'Specular':
  259. maps.specularMap = texture;
  260. maps.specular = 0xffffff;
  261. break;
  262. case 'Luminous':
  263. maps.emissiveMap = texture;
  264. maps.emissive = 0x808080;
  265. break;
  266. case 'Luminous THREE.Color':
  267. maps.emissive = 0x808080;
  268. break;
  269. case 'Metallic':
  270. maps.metalnessMap = texture;
  271. maps.metalness = 1;
  272. break;
  273. case 'Transparency':
  274. case 'Alpha':
  275. maps.alphaMap = texture;
  276. maps.transparent = true;
  277. break;
  278. case 'Normal':
  279. maps.normalMap = texture;
  280. if ( node.amplitude !== undefined ) maps.normalScale = new THREE.Vector2( node.amplitude, node.amplitude );
  281. break;
  282. case 'Bump':
  283. maps.bumpMap = texture;
  284. break;
  285. }
  286. }
  287. // LWO BSDF materials can have both spec and rough, but this is not valid in three
  288. if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;
  289. return maps;
  290. }
  291. // maps can also be defined on individual material attributes, parse those here
  292. // This occurs on Standard (Phong) surfaces
  293. parseAttributeImageMaps( attributes, textures, maps ) {
  294. for ( const name in attributes ) {
  295. const attribute = attributes[ name ];
  296. if ( attribute.maps ) {
  297. const mapData = attribute.maps[ 0 ];
  298. const path = this.getTexturePathByIndex( mapData.imageIndex, textures );
  299. if ( ! path ) return;
  300. const texture = this.loadTexture( path );
  301. if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
  302. if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );
  303. switch ( name ) {
  304. case 'Color':
  305. maps.map = texture;
  306. break;
  307. case 'Diffuse':
  308. maps.aoMap = texture;
  309. break;
  310. case 'Roughness':
  311. maps.roughnessMap = texture;
  312. maps.roughness = 1;
  313. break;
  314. case 'Specular':
  315. maps.specularMap = texture;
  316. maps.specular = 0xffffff;
  317. break;
  318. case 'Luminosity':
  319. maps.emissiveMap = texture;
  320. maps.emissive = 0x808080;
  321. break;
  322. case 'Metallic':
  323. maps.metalnessMap = texture;
  324. maps.metalness = 1;
  325. break;
  326. case 'Transparency':
  327. case 'Alpha':
  328. maps.alphaMap = texture;
  329. maps.transparent = true;
  330. break;
  331. case 'Normal':
  332. maps.normalMap = texture;
  333. break;
  334. case 'Bump':
  335. maps.bumpMap = texture;
  336. break;
  337. }
  338. }
  339. }
  340. }
  341. parseAttributes( attributes, maps ) {
  342. const params = {};
  343. // don't use color data if color map is present
  344. if ( attributes.Color && ! maps.map ) {
  345. params.color = new THREE.Color().fromArray( attributes.Color.value );
  346. } else params.color = new THREE.Color();
  347. if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {
  348. params.opacity = 1 - attributes.Transparency.value;
  349. params.transparent = true;
  350. }
  351. if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;
  352. this.parsePhysicalAttributes( params, attributes, maps );
  353. this.parseStandardAttributes( params, attributes, maps );
  354. this.parsePhongAttributes( params, attributes, maps );
  355. return params;
  356. }
  357. parsePhysicalAttributes( params, attributes /*, maps*/ ) {
  358. if ( attributes.Clearcoat && attributes.Clearcoat.value > 0 ) {
  359. params.clearcoat = attributes.Clearcoat.value;
  360. if ( attributes[ 'Clearcoat Gloss' ] ) {
  361. params.clearcoatRoughness = 0.5 * ( 1 - attributes[ 'Clearcoat Gloss' ].value );
  362. }
  363. }
  364. }
  365. parseStandardAttributes( params, attributes, maps ) {
  366. if ( attributes.Luminous ) {
  367. params.emissiveIntensity = attributes.Luminous.value;
  368. if ( attributes[ 'Luminous THREE.Color' ] && ! maps.emissive ) {
  369. params.emissive = new THREE.Color().fromArray( attributes[ 'Luminous THREE.Color' ].value );
  370. } else {
  371. params.emissive = new THREE.Color( 0x808080 );
  372. }
  373. }
  374. if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
  375. if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;
  376. }
  377. parsePhongAttributes( params, attributes, maps ) {
  378. if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 0.98 / attributes[ 'Refraction Index' ].value;
  379. if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );
  380. if ( attributes.Reflection ) {
  381. params.reflectivity = attributes.Reflection.value;
  382. params.combine = THREE.AddOperation;
  383. }
  384. if ( attributes.Luminosity ) {
  385. params.emissiveIntensity = attributes.Luminosity.value;
  386. if ( ! maps.emissiveMap && ! maps.map ) {
  387. params.emissive = params.color;
  388. } else {
  389. params.emissive = new THREE.Color( 0x808080 );
  390. }
  391. }
  392. // parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
  393. if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) {
  394. if ( attributes[ 'Color Highlight' ] ) {
  395. params.specular = new THREE.Color().setScalar( attributes.Specular.value ).lerp( params.color.clone().multiplyScalar( attributes.Specular.value ), attributes[ 'Color Highlight' ].value );
  396. } else {
  397. params.specular = new THREE.Color().setScalar( attributes.Specular.value );
  398. }
  399. }
  400. if ( params.specular && attributes.Glossiness ) params.shininess = 7 + Math.pow( 2, attributes.Glossiness.value * 12 + 2 );
  401. }
  402. parseEnvMap( connections, maps, attributes ) {
  403. if ( connections.envMap ) {
  404. const envMap = this.loadTexture( connections.envMap );
  405. if ( attributes.transparent && attributes.opacity < 0.999 ) {
  406. envMap.mapping = THREE.EquirectangularRefractionMapping;
  407. // Reflectivity and refraction mapping don't work well together in Phong materials
  408. if ( attributes.reflectivity !== undefined ) {
  409. delete attributes.reflectivity;
  410. delete attributes.combine;
  411. }
  412. if ( attributes.metalness !== undefined ) {
  413. attributes.metalness = 1; // For most transparent materials metalness should be set to 1 if not otherwise defined. If set to 0 no refraction will be visible
  414. }
  415. attributes.opacity = 1; // transparency fades out refraction, forcing opacity to 1 ensures a closer visual match to the material in Lightwave.
  416. } else envMap.mapping = THREE.EquirectangularReflectionMapping;
  417. maps.envMap = envMap;
  418. }
  419. }
  420. // get texture defined at top level by its index
  421. getTexturePathByIndex( index ) {
  422. let fileName = '';
  423. if ( ! _lwoTree.textures ) return fileName;
  424. _lwoTree.textures.forEach( function ( texture ) {
  425. if ( texture.index === index ) fileName = texture.fileName;
  426. } );
  427. return fileName;
  428. }
  429. loadTexture( path ) {
  430. if ( ! path ) return null;
  431. const texture = this.textureLoader.load( path, undefined, undefined, function () {
  432. console.warn( 'LWOLoader: non-standard resource hierarchy. Use \`resourcePath\` parameter to specify root content directory.' );
  433. } );
  434. return texture;
  435. }
  436. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  437. getWrappingType( num ) {
  438. switch ( num ) {
  439. case 0:
  440. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  441. return THREE.ClampToEdgeWrapping;
  442. case 1:
  443. return THREE.RepeatWrapping;
  444. case 2:
  445. return THREE.MirroredRepeatWrapping;
  446. case 3:
  447. return THREE.ClampToEdgeWrapping;
  448. }
  449. }
  450. getMaterialType( nodeData ) {
  451. if ( nodeData.Clearcoat && nodeData.Clearcoat.value > 0 ) return THREE.MeshPhysicalMaterial;
  452. if ( nodeData.Roughness ) return THREE.MeshStandardMaterial;
  453. return THREE.MeshPhongMaterial;
  454. }
  455. }
  456. class GeometryParser {
  457. parse( geoData, layer ) {
  458. const geometry = new THREE.BufferGeometry();
  459. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( geoData.points, 3 ) );
  460. const indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  461. geometry.setIndex( indices );
  462. this.parseGroups( geometry, geoData );
  463. geometry.computeVertexNormals();
  464. this.parseUVs( geometry, layer, indices );
  465. this.parseMorphTargets( geometry, layer, indices );
  466. // TODO: z may need to be reversed to account for coordinate system change
  467. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );
  468. // let userData = geometry.userData;
  469. // geometry = geometry.toNonIndexed()
  470. // geometry.userData = userData;
  471. return geometry;
  472. }
  473. // split quads into tris
  474. splitIndices( indices, polygonDimensions ) {
  475. const remappedIndices = [];
  476. let i = 0;
  477. polygonDimensions.forEach( function ( dim ) {
  478. if ( dim < 4 ) {
  479. for ( let k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  480. } else if ( dim === 4 ) {
  481. remappedIndices.push( indices[ i ], indices[ i + 1 ], indices[ i + 2 ], indices[ i ], indices[ i + 2 ], indices[ i + 3 ] );
  482. } else if ( dim > 4 ) {
  483. for ( let k = 1; k < dim - 1; k ++ ) {
  484. remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );
  485. }
  486. console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  487. }
  488. i += dim;
  489. } );
  490. return remappedIndices;
  491. }
  492. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  493. parseGroups( geometry, geoData ) {
  494. const tags = _lwoTree.tags;
  495. const matNames = [];
  496. let elemSize = 3;
  497. if ( geoData.type === 'lines' ) elemSize = 2;
  498. if ( geoData.type === 'points' ) elemSize = 1;
  499. const remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  500. let indexNum = 0; // create new indices in numerical order
  501. const indexPairs = {}; // original indices mapped to numerical indices
  502. let prevMaterialIndex;
  503. let materialIndex;
  504. let prevStart = 0;
  505. let currentCount = 0;
  506. for ( let i = 0; i < remappedIndices.length; i += 2 ) {
  507. materialIndex = remappedIndices[ i + 1 ];
  508. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  509. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  510. if ( materialIndex !== prevMaterialIndex ) {
  511. let currentIndex;
  512. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  513. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  514. } else {
  515. currentIndex = indexNum;
  516. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  517. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  518. indexNum ++;
  519. }
  520. geometry.addGroup( prevStart, currentCount, currentIndex );
  521. prevStart += currentCount;
  522. prevMaterialIndex = materialIndex;
  523. currentCount = 0;
  524. }
  525. currentCount += elemSize;
  526. }
  527. // the loop above doesn't add the last group, do that here.
  528. if ( geometry.groups.length > 0 ) {
  529. let currentIndex;
  530. if ( indexPairs[ tags[ materialIndex ] ] ) {
  531. currentIndex = indexPairs[ tags[ materialIndex ] ];
  532. } else {
  533. currentIndex = indexNum;
  534. indexPairs[ tags[ materialIndex ] ] = indexNum;
  535. matNames[ indexNum ] = tags[ materialIndex ];
  536. }
  537. geometry.addGroup( prevStart, currentCount, currentIndex );
  538. }
  539. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  540. geometry.userData.matNames = matNames;
  541. }
  542. splitMaterialIndices( polygonDimensions, indices ) {
  543. const remappedIndices = [];
  544. polygonDimensions.forEach( function ( dim, i ) {
  545. if ( dim <= 3 ) {
  546. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  547. } else if ( dim === 4 ) {
  548. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  549. } else {
  550. // ignore > 4 for now
  551. for ( let k = 0; k < dim - 2; k ++ ) {
  552. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  553. }
  554. }
  555. } );
  556. return remappedIndices;
  557. }
  558. // UV maps:
  559. // 1: are defined via index into an array of points, not into a geometry
  560. // - the geometry is also defined by an index into this array, but the indexes may not match
  561. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  562. // with preference given to the first map encountered
  563. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  564. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  565. // UV maps are defined as partially VMAP and partially VMAD
  566. // VMADs are currently not supported
  567. parseUVs( geometry, layer ) {
  568. // start by creating a UV map set to zero for the whole geometry
  569. const remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  570. return 0;
  571. } );
  572. for ( const name in layer.uvs ) {
  573. const uvs = layer.uvs[ name ].uvs;
  574. const uvIndices = layer.uvs[ name ].uvIndices;
  575. uvIndices.forEach( function ( i, j ) {
  576. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  577. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  578. } );
  579. }
  580. geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( remappedUVs, 2 ) );
  581. }
  582. parseMorphTargets( geometry, layer ) {
  583. let num = 0;
  584. for ( const name in layer.morphTargets ) {
  585. const remappedPoints = geometry.attributes.position.array.slice();
  586. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  587. const morphPoints = layer.morphTargets[ name ].points;
  588. const morphIndices = layer.morphTargets[ name ].indices;
  589. const type = layer.morphTargets[ name ].type;
  590. morphIndices.forEach( function ( i, j ) {
  591. if ( type === 'relative' ) {
  592. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  593. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  594. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  595. } else {
  596. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  597. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  598. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  599. }
  600. } );
  601. geometry.morphAttributes.position[ num ] = new THREE.Float32BufferAttribute( remappedPoints, 3 );
  602. geometry.morphAttributes.position[ num ].name = name;
  603. num ++;
  604. }
  605. geometry.morphTargetsRelative = false;
  606. }
  607. }
  608. // ************** UTILITY FUNCTIONS **************
  609. function extractParentUrl( url, dir ) {
  610. const index = url.indexOf( dir );
  611. if ( index === - 1 ) return './';
  612. return url.slice( 0, index );
  613. }
  614. THREE.LWOLoader = LWOLoader;
  615. } )();