2
0

LWOLoader.js 23 KB

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