LWOLoader.js 24 KB

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