LWOLoader.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. import {
  2. AddOperation,
  3. BackSide,
  4. BufferGeometry,
  5. ClampToEdgeWrapping,
  6. Color,
  7. DoubleSide,
  8. EquirectangularReflectionMapping,
  9. EquirectangularRefractionMapping,
  10. FileLoader,
  11. Float32BufferAttribute,
  12. FrontSide,
  13. LineBasicMaterial,
  14. LineSegments,
  15. Loader,
  16. Mesh,
  17. MeshPhongMaterial,
  18. MeshPhysicalMaterial,
  19. MeshStandardMaterial,
  20. MirroredRepeatWrapping,
  21. Points,
  22. PointsMaterial,
  23. RepeatWrapping,
  24. SRGBColorSpace,
  25. TextureLoader,
  26. Vector2,
  27. Vector3
  28. } from 'three';
  29. import { IFFParser } from './lwo/IFFParser.js';
  30. let _lwoTree;
  31. /**
  32. * A loader for the LWO format.
  33. *
  34. * LWO3 and LWO2 formats are supported.
  35. *
  36. * References:
  37. * - [LWO3 format specification](https://static.lightwave3d.com/sdk/2019/html/filefmts/lwo3.html)
  38. * - [LWO2 format specification](https://static.lightwave3d.com/sdk/2019/html/filefmts/lwo2.html)
  39. *
  40. * ```js
  41. * const loader = new LWOLoader();
  42. * const lwoData = await loader.loadAsync( 'models/lwo/Objects/LWO3/Demo.lwo' );
  43. *
  44. * const mesh = object.meshes[ 0 ];
  45. * scene.add( mesh );
  46. * ```
  47. *
  48. * @augments Loader
  49. * @three_import import { LWOLoader } from 'three/addons/loaders/LWOLoader.js';
  50. */
  51. class LWOLoader extends Loader {
  52. /**
  53. * Constructs a new LWO loader.
  54. *
  55. * @param {LoadingManager} [manager] - The loading manager.
  56. */
  57. constructor( manager ) {
  58. super( manager );
  59. }
  60. /**
  61. * Starts loading from the given URL and passes the loaded LWO asset
  62. * to the `onLoad()` callback.
  63. *
  64. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  65. * @param {function({meshes:Array<Mesh>,materials:Array<Material>})} onLoad - Executed when the loading process has been finished.
  66. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  67. * @param {onErrorCallback} onError - Executed when errors occur.
  68. */
  69. load( url, onLoad, onProgress, onError ) {
  70. const scope = this;
  71. const path = ( scope.path === '' ) ? extractParentUrl( url, 'Objects' ) : scope.path;
  72. // give the mesh a default name based on the filename
  73. const modelName = url.split( path ).pop().split( '.' )[ 0 ];
  74. const loader = new FileLoader( this.manager );
  75. loader.setPath( scope.path );
  76. loader.setResponseType( 'arraybuffer' );
  77. loader.load( url, function ( buffer ) {
  78. // console.time( 'Total parsing: ' );
  79. try {
  80. onLoad( scope.parse( buffer, path, modelName ) );
  81. } catch ( e ) {
  82. if ( onError ) {
  83. onError( e );
  84. } else {
  85. console.error( e );
  86. }
  87. scope.manager.itemError( url );
  88. }
  89. // console.timeEnd( 'Total parsing: ' );
  90. }, onProgress, onError );
  91. }
  92. /**
  93. * Parses the given LWO data and returns the resulting meshes and materials.
  94. *
  95. * @param {ArrayBuffer} iffBuffer - The raw LWO data as an array buffer.
  96. * @param {string} path - The URL base path.
  97. * @param {string} modelName - The model name.
  98. * @return {{meshes:Array<Mesh>,materials:Array<Material>}} An object holding the parse meshes and materials.
  99. */
  100. parse( iffBuffer, path, modelName ) {
  101. _lwoTree = new IFFParser().parse( iffBuffer );
  102. // console.log( 'lwoTree', lwoTree );
  103. const textureLoader = new TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  104. return new LWOTreeParser( textureLoader ).parse( modelName );
  105. }
  106. }
  107. // Parse the lwoTree object
  108. class LWOTreeParser {
  109. constructor( textureLoader ) {
  110. this.textureLoader = textureLoader;
  111. }
  112. parse( modelName ) {
  113. this.materials = new MaterialParser( this.textureLoader ).parse();
  114. this.defaultLayerName = modelName;
  115. this.meshes = this.parseLayers();
  116. return {
  117. materials: this.materials,
  118. meshes: this.meshes,
  119. };
  120. }
  121. parseLayers() {
  122. // array of all meshes for building hierarchy
  123. const meshes = [];
  124. // final array containing meshes with scene graph hierarchy set up
  125. const finalMeshes = [];
  126. const geometryParser = new GeometryParser();
  127. const scope = this;
  128. _lwoTree.layers.forEach( function ( layer ) {
  129. const geometry = geometryParser.parse( layer.geometry, layer );
  130. const mesh = scope.parseMesh( geometry, layer );
  131. meshes[ layer.number ] = mesh;
  132. if ( layer.parent === - 1 ) finalMeshes.push( mesh );
  133. else meshes[ layer.parent ].add( mesh );
  134. } );
  135. return finalMeshes;
  136. }
  137. parseMesh( geometry, layer ) {
  138. let mesh;
  139. const materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  140. if ( layer.geometry.type === 'points' ) mesh = new Points( geometry, materials );
  141. else if ( layer.geometry.type === 'lines' ) mesh = new LineSegments( geometry, materials );
  142. else mesh = new Mesh( geometry, materials );
  143. if ( layer.name ) mesh.name = layer.name;
  144. else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  145. const pivot = layer.pivot;
  146. if ( pivot[ 0 ] !== 0 || pivot[ 1 ] !== 0 || pivot[ 2 ] !== 0 ) {
  147. mesh.pivot = new Vector3( pivot[ 0 ], pivot[ 1 ], pivot[ 2 ] );
  148. }
  149. return mesh;
  150. }
  151. getMaterials( namesArray, type ) {
  152. const materials = [];
  153. const scope = this;
  154. namesArray.forEach( function ( name, i ) {
  155. materials[ i ] = scope.getMaterialByName( name );
  156. } );
  157. // convert materials to line or point mats if required
  158. if ( type === 'points' || type === 'lines' ) {
  159. materials.forEach( function ( mat, i ) {
  160. const spec = {
  161. color: mat.color,
  162. };
  163. if ( type === 'points' ) {
  164. spec.size = 0.1;
  165. spec.map = mat.map;
  166. materials[ i ] = new PointsMaterial( spec );
  167. } else if ( type === 'lines' ) {
  168. materials[ i ] = new LineBasicMaterial( spec );
  169. }
  170. } );
  171. }
  172. // if there is only one material, return that directly instead of array
  173. const filtered = materials.filter( Boolean );
  174. if ( filtered.length === 1 ) return filtered[ 0 ];
  175. return materials;
  176. }
  177. getMaterialByName( name ) {
  178. return this.materials.filter( function ( m ) {
  179. return m.name === name;
  180. } )[ 0 ];
  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 );
  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 );
  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 );
  505. this.parseMorphTargets( geometry, layer );
  506. return geometry;
  507. }
  508. // split quads into tris
  509. splitIndices( indices, polygonDimensions ) {
  510. const remappedIndices = [];
  511. let i = 0;
  512. polygonDimensions.forEach( function ( dim ) {
  513. if ( dim < 4 ) {
  514. for ( let k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  515. } else if ( dim === 4 ) {
  516. remappedIndices.push(
  517. indices[ i ],
  518. indices[ i + 1 ],
  519. indices[ i + 2 ],
  520. indices[ i ],
  521. indices[ i + 2 ],
  522. indices[ i + 3 ]
  523. );
  524. } else if ( dim > 4 ) {
  525. for ( let k = 1; k < dim - 1; k ++ ) {
  526. remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );
  527. }
  528. console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  529. }
  530. i += dim;
  531. } );
  532. return remappedIndices;
  533. }
  534. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  535. parseGroups( geometry, geoData ) {
  536. const tags = _lwoTree.tags;
  537. const matNames = [];
  538. let elemSize = 3;
  539. if ( geoData.type === 'lines' ) elemSize = 2;
  540. if ( geoData.type === 'points' ) elemSize = 1;
  541. const remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  542. let indexNum = 0; // create new indices in numerical order
  543. const indexPairs = {}; // original indices mapped to numerical indices
  544. let prevMaterialIndex;
  545. let materialIndex;
  546. let prevStart = 0;
  547. let currentCount = 0;
  548. for ( let i = 0; i < remappedIndices.length; i += 2 ) {
  549. materialIndex = remappedIndices[ i + 1 ];
  550. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  551. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  552. if ( materialIndex !== prevMaterialIndex ) {
  553. let currentIndex;
  554. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  555. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  556. } else {
  557. currentIndex = indexNum;
  558. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  559. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  560. indexNum ++;
  561. }
  562. geometry.addGroup( prevStart, currentCount, currentIndex );
  563. prevStart += currentCount;
  564. prevMaterialIndex = materialIndex;
  565. currentCount = 0;
  566. }
  567. currentCount += elemSize;
  568. }
  569. // the loop above doesn't add the last group, do that here.
  570. if ( geometry.groups.length > 0 ) {
  571. let currentIndex;
  572. if ( indexPairs[ tags[ materialIndex ] ] ) {
  573. currentIndex = indexPairs[ tags[ materialIndex ] ];
  574. } else {
  575. currentIndex = indexNum;
  576. indexPairs[ tags[ materialIndex ] ] = indexNum;
  577. matNames[ indexNum ] = tags[ materialIndex ];
  578. }
  579. geometry.addGroup( prevStart, currentCount, currentIndex );
  580. }
  581. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  582. geometry.userData.matNames = matNames;
  583. }
  584. splitMaterialIndices( polygonDimensions, indices ) {
  585. const remappedIndices = [];
  586. polygonDimensions.forEach( function ( dim, i ) {
  587. if ( dim <= 3 ) {
  588. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  589. } else if ( dim === 4 ) {
  590. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  591. } else {
  592. // ignore > 4 for now
  593. for ( let k = 0; k < dim - 2; k ++ ) {
  594. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  595. }
  596. }
  597. } );
  598. return remappedIndices;
  599. }
  600. // UV maps:
  601. // 1: are defined via index into an array of points, not into a geometry
  602. // - the geometry is also defined by an index into this array, but the indexes may not match
  603. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  604. // with preference given to the first map encountered
  605. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  606. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  607. // UV maps are defined as partially VMAP and partially VMAD
  608. // VMADs are currently not supported
  609. parseUVs( geometry, layer ) {
  610. // start by creating a UV map set to zero for the whole geometry
  611. const remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  612. return 0;
  613. } );
  614. for ( const name in layer.uvs ) {
  615. const uvs = layer.uvs[ name ].uvs;
  616. const uvIndices = layer.uvs[ name ].uvIndices;
  617. uvIndices.forEach( function ( i, j ) {
  618. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  619. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  620. } );
  621. }
  622. geometry.setAttribute( 'uv', new Float32BufferAttribute( remappedUVs, 2 ) );
  623. }
  624. parseMorphTargets( geometry, layer ) {
  625. let num = 0;
  626. for ( const name in layer.morphTargets ) {
  627. const remappedPoints = geometry.attributes.position.array.slice();
  628. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  629. const morphPoints = layer.morphTargets[ name ].points;
  630. const morphIndices = layer.morphTargets[ name ].indices;
  631. const type = layer.morphTargets[ name ].type;
  632. morphIndices.forEach( function ( i, j ) {
  633. if ( type === 'relative' ) {
  634. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  635. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  636. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  637. } else {
  638. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  639. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  640. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  641. }
  642. } );
  643. geometry.morphAttributes.position[ num ] = new Float32BufferAttribute( remappedPoints, 3 );
  644. geometry.morphAttributes.position[ num ].name = name;
  645. num ++;
  646. }
  647. geometry.morphTargetsRelative = false;
  648. }
  649. }
  650. // ************** UTILITY FUNCTIONS **************
  651. function extractParentUrl( url, dir ) {
  652. const index = url.indexOf( dir );
  653. if ( index === - 1 ) return './';
  654. return url.slice( 0, index );
  655. }
  656. export { LWOLoader };
粤ICP备19079148号