LWOLoader.js 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. TextureLoader,
  38. Vector2
  39. } from '../../../build/three.module.js';
  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 = 1;
  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 = 1;
  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 = 0.98 / 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. 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
  442. }
  443. attributes.opacity = 1; // transparency fades out refraction, forcing opacity to 1 ensures a closer visual match to the material in Lightwave.
  444. } else envMap.mapping = EquirectangularReflectionMapping;
  445. maps.envMap = envMap;
  446. }
  447. }
  448. // get texture defined at top level by its index
  449. getTexturePathByIndex( index ) {
  450. let fileName = '';
  451. if ( ! _lwoTree.textures ) return fileName;
  452. _lwoTree.textures.forEach( function ( texture ) {
  453. if ( texture.index === index ) fileName = texture.fileName;
  454. } );
  455. return fileName;
  456. }
  457. loadTexture( path ) {
  458. if ( ! path ) return null;
  459. const texture = this.textureLoader.load(
  460. path,
  461. undefined,
  462. undefined,
  463. function () {
  464. console.warn( 'LWOLoader: non-standard resource hierarchy. Use \`resourcePath\` parameter to specify root content directory.' );
  465. }
  466. );
  467. return texture;
  468. }
  469. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  470. getWrappingType( num ) {
  471. switch ( num ) {
  472. case 0:
  473. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  474. return ClampToEdgeWrapping;
  475. case 1: return RepeatWrapping;
  476. case 2: return MirroredRepeatWrapping;
  477. case 3: return ClampToEdgeWrapping;
  478. }
  479. }
  480. getMaterialType( nodeData ) {
  481. if ( nodeData.Clearcoat && nodeData.Clearcoat.value > 0 ) return MeshPhysicalMaterial;
  482. if ( nodeData.Roughness ) return MeshStandardMaterial;
  483. return MeshPhongMaterial;
  484. }
  485. }
  486. class GeometryParser {
  487. parse( geoData, layer ) {
  488. const geometry = new BufferGeometry();
  489. geometry.setAttribute( 'position', new Float32BufferAttribute( geoData.points, 3 ) );
  490. const indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  491. geometry.setIndex( indices );
  492. this.parseGroups( geometry, geoData );
  493. geometry.computeVertexNormals();
  494. this.parseUVs( geometry, layer, indices );
  495. this.parseMorphTargets( geometry, layer, indices );
  496. // TODO: z may need to be reversed to account for coordinate system change
  497. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );
  498. // let userData = geometry.userData;
  499. // geometry = geometry.toNonIndexed()
  500. // geometry.userData = userData;
  501. return geometry;
  502. }
  503. // split quads into tris
  504. splitIndices( indices, polygonDimensions ) {
  505. const remappedIndices = [];
  506. let i = 0;
  507. polygonDimensions.forEach( function ( dim ) {
  508. if ( dim < 4 ) {
  509. for ( let k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  510. } else if ( dim === 4 ) {
  511. remappedIndices.push(
  512. indices[ i ],
  513. indices[ i + 1 ],
  514. indices[ i + 2 ],
  515. indices[ i ],
  516. indices[ i + 2 ],
  517. indices[ i + 3 ]
  518. );
  519. } else if ( dim > 4 ) {
  520. for ( let k = 1; k < dim - 1; k ++ ) {
  521. remappedIndices.push( indices[ i ], indices[ i + k ], indices[ i + k + 1 ] );
  522. }
  523. console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  524. }
  525. i += dim;
  526. } );
  527. return remappedIndices;
  528. }
  529. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  530. parseGroups( geometry, geoData ) {
  531. const tags = _lwoTree.tags;
  532. const matNames = [];
  533. let elemSize = 3;
  534. if ( geoData.type === 'lines' ) elemSize = 2;
  535. if ( geoData.type === 'points' ) elemSize = 1;
  536. const remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  537. let indexNum = 0; // create new indices in numerical order
  538. const indexPairs = {}; // original indices mapped to numerical indices
  539. let prevMaterialIndex;
  540. let materialIndex;
  541. let prevStart = 0;
  542. let currentCount = 0;
  543. for ( let i = 0; i < remappedIndices.length; i += 2 ) {
  544. materialIndex = remappedIndices[ i + 1 ];
  545. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  546. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  547. if ( materialIndex !== prevMaterialIndex ) {
  548. let currentIndex;
  549. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  550. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  551. } else {
  552. currentIndex = indexNum;
  553. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  554. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  555. indexNum ++;
  556. }
  557. geometry.addGroup( prevStart, currentCount, currentIndex );
  558. prevStart += currentCount;
  559. prevMaterialIndex = materialIndex;
  560. currentCount = 0;
  561. }
  562. currentCount += elemSize;
  563. }
  564. // the loop above doesn't add the last group, do that here.
  565. if ( geometry.groups.length > 0 ) {
  566. let currentIndex;
  567. if ( indexPairs[ tags[ materialIndex ] ] ) {
  568. currentIndex = indexPairs[ tags[ materialIndex ] ];
  569. } else {
  570. currentIndex = indexNum;
  571. indexPairs[ tags[ materialIndex ] ] = indexNum;
  572. matNames[ indexNum ] = tags[ materialIndex ];
  573. }
  574. geometry.addGroup( prevStart, currentCount, currentIndex );
  575. }
  576. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  577. geometry.userData.matNames = matNames;
  578. }
  579. splitMaterialIndices( polygonDimensions, indices ) {
  580. const remappedIndices = [];
  581. polygonDimensions.forEach( function ( dim, i ) {
  582. if ( dim <= 3 ) {
  583. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  584. } else if ( dim === 4 ) {
  585. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  586. } else {
  587. // ignore > 4 for now
  588. for ( let k = 0; k < dim - 2; k ++ ) {
  589. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  590. }
  591. }
  592. } );
  593. return remappedIndices;
  594. }
  595. // UV maps:
  596. // 1: are defined via index into an array of points, not into a geometry
  597. // - the geometry is also defined by an index into this array, but the indexes may not match
  598. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  599. // with preference given to the first map encountered
  600. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  601. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  602. // UV maps are defined as partially VMAP and partially VMAD
  603. // VMADs are currently not supported
  604. parseUVs( geometry, layer ) {
  605. // start by creating a UV map set to zero for the whole geometry
  606. const remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  607. return 0;
  608. } );
  609. for ( const name in layer.uvs ) {
  610. const uvs = layer.uvs[ name ].uvs;
  611. const uvIndices = layer.uvs[ name ].uvIndices;
  612. uvIndices.forEach( function ( i, j ) {
  613. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  614. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  615. } );
  616. }
  617. geometry.setAttribute( 'uv', new Float32BufferAttribute( remappedUVs, 2 ) );
  618. }
  619. parseMorphTargets( geometry, layer ) {
  620. let num = 0;
  621. for ( const name in layer.morphTargets ) {
  622. const remappedPoints = geometry.attributes.position.array.slice();
  623. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  624. const morphPoints = layer.morphTargets[ name ].points;
  625. const morphIndices = layer.morphTargets[ name ].indices;
  626. const type = layer.morphTargets[ name ].type;
  627. morphIndices.forEach( function ( i, j ) {
  628. if ( type === 'relative' ) {
  629. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  630. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  631. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  632. } else {
  633. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  634. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  635. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  636. }
  637. } );
  638. geometry.morphAttributes.position[ num ] = new Float32BufferAttribute( remappedPoints, 3 );
  639. geometry.morphAttributes.position[ num ].name = name;
  640. num ++;
  641. }
  642. geometry.morphTargetsRelative = false;
  643. }
  644. }
  645. // ************** UTILITY FUNCTIONS **************
  646. function extractParentUrl( url, dir ) {
  647. const index = url.indexOf( dir );
  648. if ( index === - 1 ) return './';
  649. return url.substr( 0, index );
  650. }
  651. export { LWOLoader };