LWOLoader.js 23 KB

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