LWOLoader.js 23 KB

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