LWOLoader.js 23 KB

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