LWOLoader.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304
  1. /**
  2. * @author Lewy Blue https://github.com/looeee
  3. *
  4. * Load files in LWO3 format
  5. *
  6. * LWO3 format specification:
  7. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo3.html
  8. *
  9. * LWO2 format specification (not supported by this loader, however LWO3 files contain a lot from the LWO2 spec)
  10. * http://static.lightwave3d.com/sdk/2018/html/filefmts/lwo2.html
  11. *
  12. */
  13. THREE.LWOLoader = ( function () {
  14. var lwoTree;
  15. function LWOLoader( manager ) {
  16. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  17. }
  18. LWOLoader.prototype = {
  19. constructor: LWOLoader,
  20. crossOrigin: 'anonymous',
  21. load: function ( url, onLoad, onProgress, onError ) {
  22. var self = this;
  23. var path = ( self.path === undefined ) ? THREE.LoaderUtils.extractUrlBase( url ) : self.path;
  24. // give the mesh a default name based on the filename
  25. var modelName = url.split( path ).pop().split( '.' )[ 0 ];
  26. var loader = new THREE.FileLoader( this.manager );
  27. loader.setResponseType( 'arraybuffer' );
  28. loader.load( url, function ( buffer ) {
  29. console.time( 'Total parsing: ' );
  30. onLoad( self.parse( buffer, path, modelName ) );
  31. console.timeEnd( 'Total parsing: ' );
  32. }, onProgress, onError );
  33. },
  34. setCrossOrigin: function ( value ) {
  35. this.crossOrigin = value;
  36. return this;
  37. },
  38. setPath: function ( value ) {
  39. this.path = value;
  40. return this;
  41. },
  42. setResourcePath: function ( value ) {
  43. this.resourcePath = value;
  44. return this;
  45. },
  46. parse: function ( iffBuffer, path, modelName ) {
  47. lwoTree = new IFFParser().parse( iffBuffer );
  48. // console.log( 'lwoTree', lwoTree );
  49. var textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  50. return new LWOTreeParser( textureLoader ).parse( modelName );
  51. }
  52. };
  53. // Parse the lwoTree object
  54. function LWOTreeParser( textureLoader ) {
  55. this.textureLoader = textureLoader;
  56. }
  57. LWOTreeParser.prototype = {
  58. constructor: LWOTreeParser,
  59. parse: function ( modelName ) {
  60. this.materials = new MaterialParser( this.textureLoader ).parse();
  61. this.defaultLayerName = modelName;
  62. this.meshes = this.parseLayers();
  63. return {
  64. materials: this.materials,
  65. meshes: this.meshes,
  66. };
  67. },
  68. parseLayers() {
  69. var meshes = []; // array of all meshes for building hierarchy
  70. var finalMeshes = []; // final array containing meshes with hierarchy set up
  71. var geometryParser = new GeometryParser();
  72. var self = this;
  73. lwoTree.layers.forEach( function ( layer ) {
  74. var geometry = geometryParser.parse( layer.geometry, layer );
  75. var mesh = self.parseMesh( geometry, layer );
  76. meshes[ layer.number ] = mesh;
  77. if ( layer.parent === - 1 ) finalMeshes.push( mesh );
  78. else meshes[ layer.parent ].add( mesh );
  79. } );
  80. this.applyPivots( finalMeshes );
  81. return finalMeshes;
  82. },
  83. parseMesh( geometry, layer ) {
  84. var mesh;
  85. var materials = this.getMaterials( geometry.userData.matNames, layer.geometry.type );
  86. this.duplicateUVs( geometry, materials );
  87. if ( layer.geometry.type === 'points' ) mesh = new THREE.Points( geometry, materials );
  88. else if ( layer.geometry.type === 'lines' ) mesh = new THREE.LineSegments( geometry, materials );
  89. else mesh = new THREE.Mesh( geometry, materials );
  90. if ( layer.name ) mesh.name = layer.name;
  91. else mesh.name = this.defaultLayerName + '_layer_' + layer.number;
  92. mesh.userData.pivot = layer.pivot;
  93. return mesh;
  94. },
  95. // TODO: may need to be reversed for z to convert coordinates
  96. applyPivots( meshes ) {
  97. meshes.forEach( function ( mesh ) {
  98. mesh.traverse( function ( child ) {
  99. var pivot = child.userData.pivot;
  100. child.position.x += pivot[ 0 ];
  101. child.position.y += pivot[ 1 ];
  102. child.position.z += pivot[ 2 ];
  103. if ( child.parent ) {
  104. var parentPivot = child.parent.userData.pivot;
  105. child.position.x -= parentPivot[ 0 ];
  106. child.position.y -= parentPivot[ 1 ];
  107. child.position.z -= parentPivot[ 2 ];
  108. }
  109. } );
  110. } );
  111. },
  112. getMaterials( namesArray, type ) {
  113. var materials = [];
  114. var self = this;
  115. namesArray.forEach( function ( name, i ) {
  116. materials[ i ] = self.getMaterialByName( name );
  117. } );
  118. // convert materials to line or point mats if required
  119. if ( type === 'points' || type === 'lines' ) {
  120. materials.forEach( function ( mat, i ) {
  121. var spec = {
  122. color: mat.color,
  123. };
  124. if ( type === 'points' ) {
  125. spec.size = 0.1;
  126. spec.map = mat.map;
  127. spec.morphTargets = mat.morphTargets;
  128. materials[ i ] = new THREE.PointsMaterial( spec );
  129. } else if ( type === 'lines' ) {
  130. materials[ i ] = new THREE.LineBasicMaterial( spec );
  131. }
  132. } );
  133. }
  134. // if there is only one material, return that directly instead of array
  135. var filtered = materials.filter( Boolean );
  136. if ( filtered.length === 1 ) return filtered[ 0 ];
  137. return materials;
  138. },
  139. getMaterialByName( name ) {
  140. return this.materials.filter( function ( m ) {
  141. return m.name === name;
  142. } )[ 0 ];
  143. },
  144. // If the material has an aoMap, duplicate UVs
  145. duplicateUVs( geometry, materials ) {
  146. var duplicateUVs = false;
  147. if ( ! Array.isArray( materials ) ) {
  148. if ( materials.aoMap ) duplicateUVs = true;
  149. } else {
  150. materials.forEach( function ( material ) {
  151. if ( material.aoMap ) duplicateUVs = true;
  152. } );
  153. }
  154. if ( ! duplicateUVs ) return;
  155. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  156. },
  157. };
  158. function MaterialParser( textureLoader ) {
  159. this.textureLoader = textureLoader;
  160. }
  161. MaterialParser.prototype = {
  162. constructor: MaterialParser,
  163. parse: function () {
  164. var materials = [];
  165. this.textures = {};
  166. for ( var name in lwoTree.materials ) {
  167. materials.push( this.parseMaterial( lwoTree.materials[ name ], name, lwoTree.textures ) );
  168. }
  169. return materials;
  170. },
  171. parseMaterial( materialData, name, textures ) {
  172. var params = {
  173. name: name,
  174. side: this.getSide( materialData.attributes ),
  175. flatShading: this.getSmooth( materialData.attributes ),
  176. };
  177. var connections = this.parseConnections( materialData.connections, materialData.nodes );
  178. var maps = this.parseTextureNodes( connections.maps );
  179. this.parseAttributeImageMaps( connections.attributes, textures, maps, materialData.maps );
  180. var attributes = this.parseAttributes( connections.attributes, maps );
  181. this.parseEnvMap( connections, maps, attributes );
  182. params = Object.assign( maps, params );
  183. params = Object.assign( params, attributes );
  184. var type = connections.attributes.Roughness ? 'Standard' : 'Phong';
  185. return new THREE[ 'Mesh' + type + 'Material' ]( params );
  186. },
  187. // Note: converting from left to right handed coords by switching x -> -x in vertices, and
  188. // then switching mat FrontSide -> BackSide
  189. // NB: this means that THREE.FrontSide and THREE.BackSide have been switched!
  190. getSide( attributes ) {
  191. if ( ! attributes.side ) return THREE.BackSide;
  192. switch ( attributes.side ) {
  193. case 0:
  194. case 1:
  195. return THREE.BackSide;
  196. case 2: return THREE.FrontSide;
  197. case 3: return THREE.DoubleSide;
  198. }
  199. },
  200. getSmooth( attributes ) {
  201. if ( ! attributes.smooth ) return true;
  202. return ! attributes.smooth;
  203. },
  204. parseConnections( connections, nodes ) {
  205. var materialConnections = {
  206. maps: {}
  207. };
  208. var inputName = connections.inputName;
  209. var inputNodeName = connections.inputNodeName;
  210. var nodeName = connections.nodeName;
  211. var self = this;
  212. inputName.forEach( function ( name, index ) {
  213. if ( name === 'Material' ) {
  214. var matNode = self.getNodeByRefName( inputNodeName[ index ], nodes );
  215. materialConnections.attributes = matNode.attributes;
  216. materialConnections.envMap = matNode.fileName;
  217. materialConnections.name = inputNodeName[ index ];
  218. }
  219. } );
  220. nodeName.forEach( function ( name, index ) {
  221. if ( name === materialConnections.name ) {
  222. materialConnections.maps[ inputName[ index ] ] = self.getNodeByRefName( inputNodeName[ index ], nodes );
  223. }
  224. } );
  225. return materialConnections;
  226. },
  227. getNodeByRefName( refName, nodes ) {
  228. for ( var name in nodes ) {
  229. if ( nodes[ name ].refName === refName ) return nodes[ name ];
  230. }
  231. },
  232. parseTextureNodes( textureNodes ) {
  233. var maps = {};
  234. for ( name in textureNodes ) {
  235. var node = textureNodes[ name ];
  236. var path = node.fileName;
  237. if ( ! path ) return;
  238. var texture = this.loadTexture( path );
  239. if ( node.widthWrappingMode !== undefined ) texture.wrapS = this.getWrappingType( node.widthWrappingMode );
  240. if ( node.heightWrappingMode !== undefined ) texture.wrapT = this.getWrappingType( node.heightWrappingMode );
  241. switch ( name ) {
  242. case 'Color':
  243. maps.map = texture;
  244. break;
  245. case 'Roughness':
  246. maps.roughnessMap = texture;
  247. maps.roughness = 0.5;
  248. break;
  249. case 'Specular':
  250. maps.specularMap = texture;
  251. maps.specular = 0xffffff;
  252. break;
  253. case 'Luminous':
  254. maps.emissiveMap = texture;
  255. maps.emissive = 0x808080;
  256. break;
  257. case 'Metallic':
  258. maps.metalnessMap = texture;
  259. maps.metalness = 0.5;
  260. break;
  261. case 'Transparency':
  262. case 'Alpha':
  263. maps.alphaMap = texture;
  264. maps.transparent = true;
  265. break;
  266. case 'Normal':
  267. maps.normalMap = texture;
  268. if ( node.amplitude !== undefined ) maps.normalScale = new THREE.Vector2( node.amplitude, node.amplitude );
  269. break;
  270. case 'Bump':
  271. maps.bumpMap = texture;
  272. break;
  273. }
  274. }
  275. // LWO BSDF materials can have both spec and rough, but this is not valid in three
  276. if ( maps.roughnessMap && maps.specularMap ) delete maps.specularMap;
  277. return maps;
  278. },
  279. // maps can also be defined on individual material attributes, parse those here
  280. // This occurs on Standard (Phong) surfaces
  281. parseAttributeImageMaps( attributes, textures, maps ) {
  282. for ( var name in attributes ) {
  283. var attribute = attributes[ name ];
  284. if ( attribute.maps ) {
  285. var mapData = attribute.maps[ 0 ];
  286. var path = this.getTexturePathByIndex( mapData.imageIndex, textures );
  287. if ( ! path ) return;
  288. var texture = this.loadTexture( path );
  289. if ( mapData.wrap !== undefined ) texture.wrapS = this.getWrappingType( mapData.wrap.w );
  290. if ( mapData.wrap !== undefined ) texture.wrapT = this.getWrappingType( mapData.wrap.h );
  291. switch ( name ) {
  292. case 'Color':
  293. maps.map = texture;
  294. break;
  295. case 'Diffuse':
  296. maps.aoMap = texture;
  297. break;
  298. case 'Roughness':
  299. maps.roughnessMap = texture;
  300. maps.roughness = 1;
  301. break;
  302. case 'Specular':
  303. maps.specularMap = texture;
  304. maps.specular = 0xffffff;
  305. break;
  306. case 'Luminosity':
  307. maps.emissiveMap = texture;
  308. maps.emissive = 0x808080;
  309. break;
  310. case 'Metallic':
  311. maps.metalnessMap = texture;
  312. maps.metalness = 1;
  313. break;
  314. case 'Transparency':
  315. case 'Alpha':
  316. maps.alphaMap = texture;
  317. maps.transparent = true;
  318. break;
  319. case 'Normal':
  320. maps.normalMap = texture;
  321. break;
  322. case 'Bump':
  323. maps.bumpMap = texture;
  324. break;
  325. }
  326. }
  327. }
  328. },
  329. parseAttributes( attributes, maps ) {
  330. var params = {};
  331. // don't use color data if color map is present
  332. if ( attributes.Color && ! maps.map ) {
  333. params.color = new THREE.Color().fromArray( attributes.Color.value );
  334. } else params.color = new THREE.Color();
  335. if ( attributes.Transparency && attributes.Transparency.value !== 0 ) {
  336. params.opacity = 1 - attributes.Transparency.value;
  337. params.transparent = true;
  338. }
  339. if ( attributes[ 'Bump Height' ] ) params.bumpScale = attributes[ 'Bump Height' ].value * 0.1;
  340. if ( attributes[ 'Refraction Index' ] ) params.refractionRatio = 1 / attributes[ 'Refraction Index' ].value;
  341. this.parseStandardAttributes( params, attributes, maps );
  342. this.parsePhongAttributes( params, attributes, maps );
  343. return params;
  344. },
  345. parseStandardAttributes( params, attributes, maps ) {
  346. if ( attributes.Luminous && attributes.Luminous.value !== 0 && attributes[ 'Luminous Color' ] ) {
  347. var emissiveColor = attributes[ 'Luminous Color' ].value.map( function ( val ) {
  348. return val * attributes.Luminous.value;
  349. } );
  350. params.emissive = new THREE.Color().fromArray( emissiveColor );
  351. }
  352. if ( attributes.Roughness && ! maps.roughnessMap ) params.roughness = attributes.Roughness.value;
  353. if ( attributes.Metallic && ! maps.metalnessMap ) params.metalness = attributes.Metallic.value;
  354. },
  355. parsePhongAttributes( params, attributes, maps ) {
  356. if ( attributes.Diffuse ) params.color.multiplyScalar( attributes.Diffuse.value );
  357. if ( attributes.Reflection ) {
  358. params.reflectivity = attributes.Reflection.value;
  359. params.combine = THREE.AddOperation;
  360. }
  361. if ( attributes.Luminosity && ! maps.emissiveMap ) params.emissive = new THREE.Color().setScalar( attributes.Luminosity.value );
  362. if ( attributes.Glossiness !== undefined ) params.shininess = 5 + Math.pow( attributes.Glossiness.value * 7, 6 );
  363. // parse specular if there is no roughness - we will interpret the material as 'Phong' in this case
  364. if ( ! attributes.Roughness && attributes.Specular && ! maps.specularMap ) params.specular = new THREE.Color().setScalar( attributes.Specular.value * 1.5 );
  365. },
  366. parseEnvMap( connections, maps, attributes ) {
  367. if ( connections.envMap ) {
  368. var envMap = this.loadTexture( connections.envMap );
  369. if ( attributes.transparent && attributes.opacity < 0.999 ) {
  370. envMap.mapping = THREE.EquirectangularRefractionMapping;
  371. // Reflectivity and refraction mapping don't work well together in Phong materials
  372. if ( attributes.reflectivity !== undefined ) {
  373. delete attributes.reflectivity;
  374. delete attributes.combine;
  375. }
  376. if ( attributes.metalness !== undefined ) {
  377. delete attributes.metalness;
  378. }
  379. } else envMap.mapping = THREE.EquirectangularReflectionMapping;
  380. maps.envMap = envMap;
  381. }
  382. },
  383. // get texture defined at top level by its index
  384. getTexturePathByIndex( index ) {
  385. var fileName = '';
  386. if ( ! lwoTree.textures ) return fileName;
  387. lwoTree.textures.forEach( function ( texture ) {
  388. if ( texture.index === index ) fileName = texture.fileName;
  389. } );
  390. return fileName;
  391. },
  392. loadTexture( path ) {
  393. if ( ! path ) return null;
  394. return this.textureLoader.load( this.cleanPath( path ) );
  395. },
  396. // if texture files are contained in the standard "../Images"
  397. // directory, then LW stores the path as relative.
  398. // Otherwise it stores the full drive path, on windows "C:/dir/subdir/texture.jpg"
  399. cleanPath( path ) {
  400. if ( path.indexOf( 'Images' ) === 0 ) return '../' + path;
  401. return path.split( '/' ).pop().split( '\\' ).pop();
  402. },
  403. // 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  404. getWrappingType( num ) {
  405. switch ( num ) {
  406. case 0:
  407. console.warn( 'LWOLoader: "Reset" texture wrapping type is not supported in three.js' );
  408. return THREE.ClampToEdgeWrapping;
  409. case 1: return THREE.RepeatWrapping;
  410. case 2: return THREE.MirroredRepeatWrapping;
  411. case 3: return THREE.ClampToEdgeWrapping;
  412. }
  413. },
  414. getType( nodeData ) {
  415. if ( nodeData.roughness ) return 'Standard';
  416. return 'Phong';
  417. },
  418. };
  419. function GeometryParser() {}
  420. GeometryParser.prototype = {
  421. constructor: GeometryParser,
  422. parse( geoData, layer ) {
  423. var geometry = new THREE.BufferGeometry();
  424. geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geoData.points, 3 ) );
  425. var indices = this.splitIndices( geoData.vertexIndices, geoData.polygonDimensions );
  426. geometry.setIndex( indices );
  427. this.parseGroups( geometry, geoData );
  428. geometry.computeVertexNormals();
  429. this.parseUVs( geometry, layer, indices );
  430. this.parseMorphTargets( geometry, layer, indices );
  431. // TODO: z may need to be reversed to account for coordinate system change
  432. geometry.translate( - layer.pivot[ 0 ], - layer.pivot[ 1 ], - layer.pivot[ 2 ] );
  433. // var userData = geometry.userData;
  434. // geometry = geometry.toNonIndexed()
  435. // geometry.userData = userData;
  436. return geometry;
  437. },
  438. // split quads into tris
  439. splitIndices( indices, polygonDimensions ) {
  440. var remappedIndices = [];
  441. var i = 0;
  442. polygonDimensions.forEach( function ( dim ) {
  443. if ( dim < 4 ) {
  444. for ( var k = 0; k < dim; k ++ ) remappedIndices.push( indices[ i + k ] );
  445. } else if ( dim === 4 ) {
  446. remappedIndices.push(
  447. indices[ i ],
  448. indices[ i + 1 ],
  449. indices[ i + 2 ],
  450. indices[ i ],
  451. indices[ i + 2 ],
  452. indices[ i + 3 ]
  453. );
  454. } else if ( dim > 4 ) console.warn( 'LWOLoader: polygons with greater than 4 sides are not supported' );
  455. i += dim;
  456. } );
  457. return remappedIndices;
  458. },
  459. // NOTE: currently ignoring poly indices and assuming that they are intelligently ordered
  460. parseGroups( geometry, geoData ) {
  461. var tags = lwoTree.tags;
  462. var matNames = [];
  463. var elemSize = 3;
  464. if ( geoData.type === 'lines' ) elemSize = 2;
  465. if ( geoData.type === 'points' ) elemSize = 1;
  466. var remappedIndices = this.splitMaterialIndices( geoData.polygonDimensions, geoData.materialIndices );
  467. var indexNum = 0; // create new indices in numerical order
  468. var indexPairs = {}; // original indices mapped to numerical indices
  469. var prevMaterialIndex;
  470. var prevStart = 0;
  471. var currentCount = 0;
  472. for ( var i = 0; i < remappedIndices.length; i += 2 ) {
  473. var materialIndex = remappedIndices[ i + 1 ];
  474. if ( i === 0 ) matNames[ indexNum ] = tags[ materialIndex ];
  475. if ( prevMaterialIndex === undefined ) prevMaterialIndex = materialIndex;
  476. if ( materialIndex !== prevMaterialIndex ) {
  477. var currentIndex;
  478. if ( indexPairs[ tags[ prevMaterialIndex ] ] ) {
  479. currentIndex = indexPairs[ tags[ prevMaterialIndex ] ];
  480. } else {
  481. currentIndex = indexNum;
  482. indexPairs[ tags[ prevMaterialIndex ] ] = indexNum;
  483. matNames[ indexNum ] = tags[ prevMaterialIndex ];
  484. indexNum ++;
  485. }
  486. geometry.addGroup( prevStart, currentCount, currentIndex );
  487. prevStart += currentCount;
  488. prevMaterialIndex = materialIndex;
  489. currentCount = 0;
  490. }
  491. currentCount += elemSize;
  492. }
  493. // the loop above doesn't add the last group, do that here.
  494. if ( geometry.groups.length > 0 ) {
  495. var currentIndex;
  496. if ( indexPairs[ tags[ materialIndex ] ] ) {
  497. currentIndex = indexPairs[ tags[ materialIndex ] ];
  498. } else {
  499. currentIndex = indexNum;
  500. indexPairs[ tags[ materialIndex ] ] = indexNum;
  501. matNames[ indexNum ] = tags[ materialIndex ];
  502. }
  503. geometry.addGroup( prevStart, currentCount, currentIndex );
  504. }
  505. // Mat names from TAGS chunk, used to build up an array of materials for this geometry
  506. geometry.userData.matNames = matNames;
  507. },
  508. splitMaterialIndices( polygonDimensions, indices ) {
  509. var remappedIndices = [];
  510. polygonDimensions.forEach( function ( dim, i ) {
  511. if ( dim <= 3 ) {
  512. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ] );
  513. } else if ( dim === 4 ) {
  514. remappedIndices.push( indices[ i * 2 ], indices[ i * 2 + 1 ], indices[ i * 2 ], indices[ i * 2 + 1 ] );
  515. } // ignore > 4 for now
  516. } );
  517. return remappedIndices;
  518. },
  519. // UV maps:
  520. // 1: are defined via index into an array of points, not into a geometry
  521. // - the geometry is also defined by an index into this array, but the indexes may not match
  522. // 2: there can be any number of UV maps for a single geometry. Here these are combined,
  523. // with preference given to the first map encountered
  524. // 3: UV maps can be partial - that is, defined for only a part of the geometry
  525. // 4: UV maps can be VMAP or VMAD (discontinuous, to allow for seams). In practice, most
  526. // UV maps are defined as partially VMAP and partially VMAD
  527. // VMADs are currently not supported
  528. parseUVs( geometry, layer ) {
  529. // start by creating a UV map set to zero for the whole geometry
  530. var remappedUVs = Array.from( Array( geometry.attributes.position.count * 2 ), function () {
  531. return 0;
  532. } );
  533. for ( var name in layer.uvs ) {
  534. var uvs = layer.uvs[ name ].uvs;
  535. var uvIndices = layer.uvs[ name ].uvIndices;
  536. uvIndices.forEach( function ( i, j ) {
  537. remappedUVs[ i * 2 ] = uvs[ j * 2 ];
  538. remappedUVs[ i * 2 + 1 ] = uvs[ j * 2 + 1 ];
  539. } );
  540. }
  541. geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( remappedUVs, 2 ) );
  542. },
  543. parseMorphTargets( geometry, layer ) {
  544. var num = 0;
  545. for ( var name in layer.morphTargets ) {
  546. var remappedPoints = geometry.attributes.position.array.slice();
  547. if ( ! geometry.morphAttributes.position ) geometry.morphAttributes.position = [];
  548. var morphPoints = layer.morphTargets[ name ].points;
  549. var morphIndices = layer.morphTargets[ name ].indices;
  550. var type = layer.morphTargets[ name ].type;
  551. morphIndices.forEach( function ( i, j ) {
  552. if ( type === 'relative' ) {
  553. remappedPoints[ i * 3 ] += morphPoints[ j * 3 ];
  554. remappedPoints[ i * 3 + 1 ] += morphPoints[ j * 3 + 1 ];
  555. remappedPoints[ i * 3 + 2 ] += morphPoints[ j * 3 + 2 ];
  556. } else {
  557. remappedPoints[ i * 3 ] = morphPoints[ j * 3 ];
  558. remappedPoints[ i * 3 + 1 ] = morphPoints[ j * 3 + 1 ];
  559. remappedPoints[ i * 3 + 2 ] = morphPoints[ j * 3 + 2 ];
  560. }
  561. } );
  562. geometry.morphAttributes.position[ num ] = new THREE.Float32BufferAttribute( remappedPoints, 3 );
  563. geometry.morphAttributes.position[ num ].name = name;
  564. num ++;
  565. }
  566. },
  567. };
  568. // parse data from the IFF buffer.
  569. // LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
  570. //
  571. // ATOMIC DATA TYPES
  572. // ID Tag - 4x 7 bit uppercase ASCII chars: ID4
  573. // signed integer, 1, 2, or 4 byte length: I1, I2, I4
  574. // unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
  575. // float, 4 byte length: F4
  576. // string, series of ASCII chars followed by null byte (If the length of the string including the null terminating byte is odd, an extra null is added so that the data that follows will begin on an even byte boundary): S0
  577. //
  578. // COMPOUND DATA TYPES
  579. // Variable-length Index (index into an array or collection): U2 or U4 : VX
  580. // Color (RGB): F4 + F4 + F4: COL12
  581. // Coordinate (x, y, z): F4 + F4 + F4: VEC12
  582. // Percentage F4 data type from 0->1 with 1 = 100%: FP4
  583. // Angle in radian F4: ANG4
  584. // Filename (string) S0: FNAM0
  585. // XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
  586. // XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
  587. //
  588. // The IFF file is arranged in chunks:
  589. // CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
  590. // optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
  591. // Chunks are combined in Forms (collections of chunks)
  592. // FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
  593. // CHUNKS and FORMS are collectively referred to as blocks
  594. // The entire file is contained in one top level FORM
  595. function IFFParser() {}
  596. IFFParser.prototype = {
  597. constructor: IFFParser,
  598. parse: function ( buffer ) {
  599. // dump the whole buffer as a string for testing
  600. // printBuffer( buffer );
  601. this.reader = new DataViewReader( buffer );
  602. this.tree = {
  603. materials: {},
  604. layers: [],
  605. tags: [],
  606. textures: [],
  607. };
  608. // start out at the top level to add any data before first layer is encountered
  609. this.currentLayer = this.tree;
  610. this.currentForm = this.tree;
  611. // parse blocks until end of file is reached
  612. while ( ! this.reader.endOfFile() ) this.parseBlock();
  613. return this.tree;
  614. },
  615. parseBlock() {
  616. var blockID = this.reader.getIDTag();
  617. var length = this.reader.getUint32(); // size of data in bytes
  618. // Data types may be found in either LWO2 OR LWO3 spec
  619. switch ( blockID ) {
  620. case 'FORM': // form blocks may consist of sub -chunks or sub-forms
  621. this.parseForm( length );
  622. break;
  623. // SKIPPED CHUNKS
  624. // MISC skipped
  625. case 'ICON': // Thumbnail Icon Image
  626. case 'VMPA': // Vertex Map Parameter
  627. case 'BBOX': // bounding box
  628. // case 'VMMD':
  629. // case 'VTYP':
  630. // normal maps can be specified, normally on models imported from other applications. Currently ignored
  631. case 'NORM':
  632. // ENVL FORM skipped
  633. case 'PRE ':
  634. case 'POST':
  635. case 'KEY ':
  636. case 'SPAN':
  637. // CLIP FORM skipped
  638. case 'TIME':
  639. case 'CLRS':
  640. case 'CLRA':
  641. case 'FILT':
  642. case 'DITH':
  643. case 'CONT':
  644. case 'BRIT':
  645. case 'SATR':
  646. case 'HUE ':
  647. case 'GAMM':
  648. case 'NEGA':
  649. case 'IFLT':
  650. case 'PFLT':
  651. // Image Map Layer skipped
  652. case 'PROJ':
  653. case 'AXIS':
  654. case 'AAST':
  655. case 'PIXB':
  656. case 'STCK':
  657. // Procedural Textures skipped
  658. case 'VALU':
  659. // Gradient Textures skipped
  660. case 'PNAM':
  661. case 'INAM':
  662. case 'GRST':
  663. case 'GREN':
  664. case 'GRPT':
  665. case 'FKEY':
  666. case 'IKEY':
  667. // Texture Mapping Form skipped
  668. case 'CSYS':
  669. // Surface CHUNKs skipped
  670. case 'OPAQ': // top level 'opacity' checkbox
  671. case 'CMAP': // clip map
  672. // Surface node CHUNKS skipped
  673. // These mainly specify the node editor setup in LW
  674. case 'NLOC':
  675. case 'NZOM':
  676. case 'NVER':
  677. case 'NSRV':
  678. case 'NCRD':
  679. case 'NMOD':
  680. case 'NPRW':
  681. case 'NPLA':
  682. case 'VERS':
  683. case 'ENUM':
  684. case 'FLAG':
  685. case 'TAG ':
  686. // Car Material CHUNKS
  687. case 'CGMD':
  688. case 'CGTY':
  689. case 'CGST':
  690. case 'CGEN':
  691. case 'CGTS':
  692. case 'CGTE':
  693. case 'OSMP':
  694. case 'OMDE':
  695. case 'OUTR':
  696. this.reader.skip( length );
  697. break;
  698. // Skipped LWO2 chunks
  699. case 'DIFF': // diffuse level, may be necessary to modulate COLR with this
  700. case 'TRNL':
  701. case 'REFL':
  702. case 'GLOS':
  703. case 'SHRP':
  704. case 'RFOP':
  705. case 'RSAN':
  706. case 'TROP':
  707. case 'RBLR':
  708. case 'TBLR':
  709. case 'CLRH':
  710. case 'CLRF':
  711. case 'ADTR':
  712. case 'GLOW':
  713. case 'LINE':
  714. case 'ALPH':
  715. case 'LINE':
  716. case 'VCOL':
  717. case 'ENAB':
  718. this.reader.skip( length );
  719. break;
  720. // Texture node chunks (not in spec)
  721. case 'IPIX': // usePixelBlending
  722. case 'IMIP': // useMipMaps
  723. case 'IMOD': // imageBlendingMode
  724. case 'AMOD': // unknown
  725. case 'IINV': // imageInvertAlpha
  726. case 'INCR': // imageInvertColor
  727. case 'IAXS': // imageAxis ( for non-UV maps)
  728. case 'IFOT': // imageFallofType
  729. case 'ITIM': // timing for animated textures
  730. case 'IWRL':
  731. case 'IUTI':
  732. case 'IINX':
  733. case 'IINY':
  734. case 'IINZ':
  735. case 'IREF': // possibly a VX for reused texture nodes
  736. if ( length === 4 ) this.currentNode[ blockID ] = this.reader.getInt32();
  737. else this.reader.skip( length );
  738. break;
  739. case 'OTAG':
  740. this.parseObjectTag();
  741. break;
  742. case 'LAYR':
  743. this.parseLayer( length );
  744. break;
  745. case 'PNTS':
  746. this.parsePoints( length );
  747. break;
  748. case 'VMAP':
  749. this.parseVertexMapping( length );
  750. break;
  751. case 'POLS':
  752. this.parsePolygonList( length );
  753. break;
  754. case 'TAGS':
  755. this.parseTagStrings( length );
  756. break;
  757. case 'PTAG':
  758. this.parsePolygonTagMapping( length );
  759. break;
  760. case 'VMAD':
  761. this.parseVertexMapping( length, true );
  762. break;
  763. // Misc CHUNKS
  764. case 'DESC': // Description Line
  765. this.currentForm.description = this.reader.getString();
  766. break;
  767. case 'TEXT':
  768. case 'CMNT':
  769. case 'NCOM':
  770. this.currentForm.comment = this.reader.getString();
  771. break;
  772. // Envelope Form
  773. case 'NAME':
  774. this.currentForm.channelName = this.reader.getString();
  775. break;
  776. // Image Map Layer
  777. case 'WRAP':
  778. this.currentForm.wrap = { w: this.reader.getUint16(), h: this.reader.getUint16() };
  779. break;
  780. case 'IMAG':
  781. var index = this.reader.getVariableLengthIndex();
  782. this.currentForm.imageIndex = index;
  783. break;
  784. // Texture Mapping Form
  785. case 'OREF':
  786. this.currentForm.referenceObject = this.reader.getString();
  787. break;
  788. case 'ROID':
  789. this.currentForm.referenceObjectID = this.reader.getUint32();
  790. break;
  791. // Surface Blocks
  792. case 'SSHN':
  793. this.currentSurface.surfaceShaderName = this.reader.getString();
  794. break;
  795. case 'AOVN':
  796. this.currentSurface.surfaceCustomAOVName = this.reader.getString();
  797. break;
  798. // Nodal Blocks
  799. case 'NSTA':
  800. this.currentForm.disabled = this.reader.getUint16();
  801. break;
  802. case 'NRNM':
  803. this.currentForm.realName = this.reader.getString();
  804. break;
  805. case 'NNME':
  806. this.currentForm.refName = this.reader.getString();
  807. this.currentSurface.nodes[ this.currentForm.refName ] = this.currentForm;
  808. break;
  809. // Nodal Blocks : connections
  810. case 'INME':
  811. if ( ! this.currentForm.nodeName ) this.currentForm.nodeName = [];
  812. this.currentForm.nodeName.push( this.reader.getString() );
  813. break;
  814. case 'IINN':
  815. if ( ! this.currentForm.inputNodeName ) this.currentForm.inputNodeName = [];
  816. this.currentForm.inputNodeName.push( this.reader.getString() );
  817. break;
  818. case 'IINM':
  819. if ( ! this.currentForm.inputName ) this.currentForm.inputName = [];
  820. this.currentForm.inputName.push( this.reader.getString() );
  821. break;
  822. case 'IONM':
  823. if ( ! this.currentForm.inputOutputName ) this.currentForm.inputOutputName = [];
  824. this.currentForm.inputOutputName.push( this.reader.getString() );
  825. break;
  826. case 'FNAM':
  827. this.currentForm.fileName = this.reader.getString();
  828. break;
  829. case 'CHAN': // NOTE: ENVL Forms may also have CHAN chunk, however ENVL is currently ignored
  830. if ( length === 4 ) this.currentForm.textureChannel = this.reader.getIDTag();
  831. else this.reader.skip( length );
  832. break;
  833. // LWO2 Spec chunks: these are needed since the SURF FORMs are often in LWO2 format
  834. case 'SMAN':
  835. var maxSmoothingAngle = this.reader.getFloat32();
  836. this.currentSurface.attributes.smooth = ( maxSmoothingAngle < 0 ) ? false : true;
  837. break;
  838. case 'ENAB':
  839. this.currentForm.enabled = this.reader.getUint16();
  840. break;
  841. // LWO2: Basic Surface Parameters
  842. case 'COLR':
  843. this.currentSurface.attributes.color = this.reader.getFloat32Array( 3 );
  844. this.reader.skip( 2 ); // VX: envelope
  845. break;
  846. case 'LUMI':
  847. this.currentSurface.attributes.luminosityLevel = this.reader.getFloat32();
  848. this.reader.skip( 2 );
  849. break;
  850. case 'SPEC':
  851. this.currentSurface.attributes.specularLevel = this.reader.getFloat32();
  852. this.reader.skip( 2 );
  853. break;
  854. case 'REFL':
  855. this.currentSurface.attributes.reflectivity = this.reader.getFloat32();
  856. this.reader.skip( 2 );
  857. break;
  858. case 'TRAN':
  859. this.currentSurface.attributes.opacity = this.reader.getFloat32();
  860. this.reader.skip( 2 );
  861. break;
  862. case 'BUMP':
  863. this.currentSurface.attributes.bumpStrength = this.reader.getFloat32();
  864. this.reader.skip( 2 );
  865. break;
  866. case 'SIDE':
  867. this.currentSurface.attributes.side = this.reader.getUint16();
  868. break;
  869. case 'RIMG':
  870. this.currentSurface.attributes.reflectionMap = this.reader.getVariableLengthIndex();
  871. break;
  872. case 'RIND':
  873. this.currentSurface.attributes.refractiveIndex = this.reader.getFloat32();
  874. this.reader.skip( 2 );
  875. break;
  876. case 'TIMG':
  877. this.currentSurface.attributes.refractionMap = this.reader.getVariableLengthIndex();
  878. break;
  879. case 'IMAP':
  880. this.currentSurface.attributes.imageMapIndex = this.reader.getUint32();
  881. break;
  882. case 'IUVI': // uv channel name
  883. this.currentNode.UVChannel = this.reader.getString( length );
  884. break;
  885. case 'IUTL': // widthWrappingMode: 0 = Reset, 1 = Repeat, 2 = Mirror, 3 = Edge
  886. this.currentNode.widthWrappingMode = this.reader.getUint32();
  887. break;
  888. case 'IVTL': // heightWrappingMode
  889. this.currentNode.heightWrappingMode = this.reader.getUint32();
  890. break;
  891. default:
  892. this.parseUnknownCHUNK( blockID, length );
  893. }
  894. if ( this.reader.offset >= this.currentFormEnd ) {
  895. this.currentForm = this.parentForm;
  896. }
  897. },
  898. ///
  899. // FORM PARSING METHODS
  900. ///
  901. // Forms are organisational and can contain any number of sub chunks and sub forms
  902. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  903. parseForm( length ) {
  904. var type = this.reader.getIDTag();
  905. switch ( type ) {
  906. // SKIPPED FORMS
  907. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  908. case 'ISEQ': // Image sequence
  909. case 'ANIM': // plug in animation
  910. case 'STCC': // Color-cycling Still
  911. case 'VPVL':
  912. case 'VPRM':
  913. case 'NROT':
  914. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  915. case 'WRPH': // image wrap h
  916. case 'FUNC':
  917. case 'FALL':
  918. case 'OPAC':
  919. case 'GRAD': // gradient texture
  920. case 'ENVS':
  921. case 'VMOP':
  922. case 'VMBG':
  923. // Car Material FORMS
  924. case 'OMAX':
  925. case 'STEX':
  926. case 'CKBG':
  927. case 'CKEY':
  928. case 'VMLA':
  929. case 'VMLB':
  930. this.skipForm( length ); // not currently supported
  931. break;
  932. // if break; is called directly, the position in the lwoTree is not created
  933. // any sub chunks and forms are added to the parent form instead
  934. case 'META':
  935. case 'NNDS':
  936. case 'NODS':
  937. case 'NDTA':
  938. case 'ADAT':
  939. case 'AOVS':
  940. case 'BLOK':
  941. // used by texture nodes
  942. case 'IBGC': // imageBackgroundColor
  943. case 'IOPC': // imageOpacity
  944. case 'IIMG': // hold reference to image path
  945. case 'TXTR':
  946. // this.setupForm( type, length );
  947. break;
  948. case 'IFAL': // imageFallof
  949. case 'ISCL': // imageScale
  950. case 'IPOS': // imagePosition
  951. case 'IROT': // imageRotation
  952. case 'IBMP':
  953. case 'IUTD':
  954. case 'IVTD':
  955. this.parseTextureNodeAttribute( type );
  956. break;
  957. case 'LWO3':
  958. this.tree.format = type;
  959. break;
  960. case 'ENVL':
  961. this.parseEnvelope( length );
  962. break;
  963. // CLIP FORM AND SUB FORMS
  964. case 'CLIP':
  965. this.parseClip( length );
  966. break;
  967. case 'STIL':
  968. this.parseImage();
  969. break;
  970. case 'XREF': // clone of another STIL
  971. this.reader.skip( 8 ); // unknown
  972. this.currentForm.referenceTexture = {
  973. index: this.reader.getUint32(),
  974. refName: this.reader.getString() // internal unique ref
  975. };
  976. break;
  977. // Not in spec, used by texture nodes
  978. case 'IMST':
  979. this.parseImageStateForm( length );
  980. break;
  981. // SURF FORM AND SUB FORMS
  982. case 'SURF':
  983. this.parseSurfaceForm( length );
  984. break;
  985. case 'VALU': // Not in spec
  986. this.parseValueForm( length );
  987. break;
  988. case 'NTAG':
  989. this.parseSubNode( length );
  990. break;
  991. case 'NNDS':
  992. this.setupForm( 'nodes', length );
  993. break;
  994. case 'ATTR': // BSDF Node Attributes
  995. case 'SATR': // Standard Node Attributes
  996. this.setupForm( 'attributes', length );
  997. break;
  998. case 'NCON':
  999. this.parseConnections( length );
  1000. break;
  1001. case 'SSHA':
  1002. this.parentForm = this.currentForm;
  1003. this.currentForm = this.currentSurface;
  1004. this.setupForm( 'surfaceShader', length );
  1005. break;
  1006. case 'SSHD':
  1007. this.setupForm( 'surfaceShaderData', length );
  1008. break;
  1009. case 'ENTR': // Not in spec
  1010. this.parseEntryForm( length );
  1011. break;
  1012. // Image Map Layer
  1013. case 'IMAP':
  1014. this.parseImageMap( length );
  1015. break;
  1016. case 'TAMP':
  1017. this.parseXVAL( 'amplitude', length );
  1018. break;
  1019. //Texture Mapping Form
  1020. case 'TMAP':
  1021. this.setupForm( 'textureMap', length );
  1022. break;
  1023. case 'CNTR':
  1024. this.parseXVAL3( 'center', length );
  1025. break;
  1026. case 'SIZE':
  1027. this.parseXVAL3( 'scale', length );
  1028. break;
  1029. case 'ROTA':
  1030. this.parseXVAL3( 'rotation', length );
  1031. break;
  1032. default:
  1033. this.parseUnknownForm( type, length );
  1034. }
  1035. },
  1036. setupForm( type, length ) {
  1037. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  1038. this.currentFormEnd = this.reader.offset + length;
  1039. this.parentForm = this.currentForm;
  1040. if ( ! this.currentForm[ type ] ) {
  1041. this.currentForm[ type ] = {};
  1042. this.currentForm = this.currentForm[ type ];
  1043. } else {
  1044. // should never see this unless there's a bug in the reader
  1045. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  1046. this.currentForm = this.currentForm[ type ];
  1047. }
  1048. },
  1049. skipForm( length ) {
  1050. this.reader.skip( length - 4 );
  1051. },
  1052. parseUnknownForm( type, length ) {
  1053. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  1054. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  1055. this.reader.skip( length - 4 );
  1056. },
  1057. parseSurfaceForm( length ) {
  1058. this.reader.skip( 8 ); // unknown Uint32 x2
  1059. var name = this.reader.getString();
  1060. var surface = {
  1061. attributes: {}, // LWO2 style non-node attributes will go here
  1062. connections: {},
  1063. name: name,
  1064. nodes: {},
  1065. source: this.reader.getString(),
  1066. };
  1067. this.tree.materials[ name ] = surface;
  1068. this.currentSurface = surface;
  1069. this.parentForm = this.tree.materials;
  1070. this.currentForm = surface;
  1071. this.currentFormEnd = this.reader.offset + length;
  1072. },
  1073. parseSubNode( length ) {
  1074. // parse the NRNM CHUNK of the subnode FORM to get
  1075. // a meaningful name for the subNode
  1076. // some subnodes can be renamed, but Input and Surface cannot
  1077. this.reader.skip( 8 ); // NRNM + length
  1078. var name = this.reader.getString();
  1079. var node = {
  1080. name: name
  1081. };
  1082. this.currentForm = node;
  1083. this.currentNode = node;
  1084. this.currentFormEnd = this.reader.offset + length;
  1085. },
  1086. // collect attributes from all nodes at the top level of a surface
  1087. parseConnections( length ) {
  1088. this.currentFormEnd = this.reader.offset + length;
  1089. this.parentForm = this.currentForm;
  1090. this.currentForm = this.currentSurface.connections;
  1091. },
  1092. // surface node attribute data, e.g. specular, roughness etc
  1093. parseEntryForm( length ) {
  1094. this.reader.skip( 8 ); // NAME + length
  1095. var name = this.reader.getString();
  1096. this.currentForm = this.currentNode.attributes;
  1097. this.setupForm( name, length );
  1098. },
  1099. // parse values from material - doesn't match up to other LWO3 data types
  1100. // sub form of entry form
  1101. parseValueForm() {
  1102. this.reader.skip( 8 ); // unknown + length
  1103. var valueType = this.reader.getString();
  1104. if ( valueType === 'double' ) {
  1105. this.currentForm.value = this.reader.getUint64();
  1106. } else if ( valueType === 'int' ) {
  1107. this.currentForm.value = this.reader.getUint32();
  1108. } else if ( valueType === 'vparam' ) {
  1109. this.reader.skip( 24 );
  1110. this.currentForm.value = this.reader.getFloat64();
  1111. } else if ( valueType === 'vparam3' ) {
  1112. this.reader.skip( 24 );
  1113. this.currentForm.value = this.reader.getFloat64Array( 3 );
  1114. }
  1115. },
  1116. // holds various data about texture node image state
  1117. // Data other thanmipMapLevel unknown
  1118. parseImageStateForm() {
  1119. this.reader.skip( 8 ); // unknown
  1120. this.currentForm.mipMapLevel = this.reader.getFloat32();
  1121. },
  1122. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  1123. parseImageMap( length ) {
  1124. this.currentFormEnd = this.reader.offset + length;
  1125. this.parentForm = this.currentForm;
  1126. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  1127. var map = {};
  1128. this.currentForm.maps.push( map );
  1129. this.currentForm = map;
  1130. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  1131. },
  1132. parseTextureNodeAttribute( type ) {
  1133. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  1134. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  1135. switch ( type ) {
  1136. case 'ISCL':
  1137. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  1138. break;
  1139. case 'IPOS':
  1140. this.currentNode.position = this.reader.getFloat32Array( 3 );
  1141. break;
  1142. case 'IROT':
  1143. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  1144. break;
  1145. case 'IFAL':
  1146. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  1147. break;
  1148. case 'IBMP':
  1149. this.currentNode.amplitude = this.reader.getFloat32();
  1150. break;
  1151. case 'IUTD':
  1152. this.currentNode.uTiles = this.reader.getFloat32();
  1153. break;
  1154. case 'IVTD':
  1155. this.currentNode.vTiles = this.reader.getFloat32();
  1156. break;
  1157. }
  1158. this.reader.skip( 2 ); // unknown
  1159. },
  1160. // ENVL forms are currently ignored
  1161. parseEnvelope( length ) {
  1162. this.reader.skip( length - 4 ); // skipping entirely for now
  1163. },
  1164. ///
  1165. // CHUNK PARSING METHODS
  1166. ///
  1167. // clips can either be defined inside a surface node, or at the top
  1168. // level and they have a different format in each case
  1169. parseClip( length ) {
  1170. var tag = this.reader.getIDTag();
  1171. // inside surface node
  1172. if ( tag === 'FORM' ) {
  1173. this.reader.skip( 16 );
  1174. this.currentNode.fileName = this.reader.getString();
  1175. return;
  1176. }
  1177. // otherwise top level
  1178. this.reader.setOffset( this.reader.offset - 4 );
  1179. this.currentFormEnd = this.reader.offset + length;
  1180. this.parentForm = this.currentForm;
  1181. this.reader.skip( 8 ); // unknown
  1182. var texture = {
  1183. index: this.reader.getUint32()
  1184. };
  1185. this.tree.textures.push( texture );
  1186. this.currentForm = texture;
  1187. },
  1188. parseImage() {
  1189. this.reader.skip( 8 ); // unknown
  1190. this.currentForm.fileName = this.reader.getString();
  1191. },
  1192. parseXVAL( type, length ) {
  1193. var endOffset = this.reader.offset + length - 4;
  1194. this.reader.skip( 8 );
  1195. this.currentForm[ type ] = this.reader.getFloat32();
  1196. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  1197. },
  1198. parseXVAL3( type, length ) {
  1199. var endOffset = this.reader.offset + length - 4;
  1200. this.reader.skip( 8 );
  1201. this.currentForm[ type ] = {
  1202. x: this.reader.getFloat32(),
  1203. y: this.reader.getFloat32(),
  1204. z: this.reader.getFloat32(),
  1205. };
  1206. this.reader.setOffset( endOffset );
  1207. },
  1208. // Tags associated with an object
  1209. // OTAG { type[ID4], tag-string[S0] }
  1210. parseObjectTag() {
  1211. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  1212. this.tree.objectTags[ this.reader.getIDTag() ] = {
  1213. tagString: this.reader.getString()
  1214. };
  1215. },
  1216. // Signals the start of a new layer. All the data chunks which follow will be included in this layer until another layer chunk is encountered.
  1217. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  1218. parseLayer( length ) {
  1219. var layer = {
  1220. number: this.reader.getUint16(),
  1221. flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
  1222. pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
  1223. name: this.reader.getString(),
  1224. };
  1225. this.tree.layers.push( layer );
  1226. this.currentLayer = layer;
  1227. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  1228. // if we have not reached then end of the layer block, there must be a parent defined
  1229. this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  1230. },
  1231. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  1232. // Converting from left to right handed coordinate system:
  1233. // x -> -x and switch material FrontSide -> BackSide
  1234. parsePoints( length ) {
  1235. this.currentPoints = [];
  1236. for ( var i = 0; i < length / 4; i += 3 ) {
  1237. // z -> -z to match three.js right handed coords
  1238. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1239. }
  1240. },
  1241. // parse VMAP or VMAD
  1242. // Associates a set of floating-point vectors with a set of points.
  1243. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  1244. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  1245. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  1246. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  1247. // if they exist. The vector values in the VMAD will then replace those in the
  1248. // corresponding VMAP, but only for calculations involving the specified polygons.
  1249. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  1250. parseVertexMapping( length, discontinuous ) {
  1251. var finalOffset = this.reader.offset + length;
  1252. var channelName = this.reader.getString();
  1253. if ( this.reader.offset === finalOffset ) {
  1254. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  1255. this.currentForm.UVChannel = channelName;
  1256. return;
  1257. }
  1258. // otherwise reset to initial length and parse normal VMAP CHUNK
  1259. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  1260. var type = this.reader.getIDTag();
  1261. this.reader.getUint16(); // dimension
  1262. var name = this.reader.getString();
  1263. var remainingLength = length - 6 - stringOffset( name );
  1264. switch ( type ) {
  1265. case 'TXUV':
  1266. this.parseUVMapping( name, finalOffset, discontinuous );
  1267. break;
  1268. case 'MORF':
  1269. case 'SPOT':
  1270. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  1271. break;
  1272. // unsupported VMAPs
  1273. case 'APSL':
  1274. case 'NORM':
  1275. case 'WGHT':
  1276. case 'MNVW':
  1277. case 'PICK':
  1278. case 'RGB ':
  1279. case 'RGBA':
  1280. this.reader.skip( remainingLength );
  1281. break;
  1282. default:
  1283. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  1284. this.reader.skip( remainingLength );
  1285. }
  1286. },
  1287. parseUVMapping( name, finalOffset, discontinuous ) {
  1288. var uvIndices = [];
  1289. var polyIndices = [];
  1290. var uvs = [];
  1291. while ( this.reader.offset < finalOffset ) {
  1292. uvIndices.push( this.reader.getVariableLengthIndex() );
  1293. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  1294. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  1295. }
  1296. if ( discontinuous ) {
  1297. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  1298. this.currentLayer.discontinuousUVs[ name ] = {
  1299. uvIndices: uvIndices,
  1300. polyIndices: polyIndices,
  1301. uvs: uvs,
  1302. };
  1303. } else {
  1304. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  1305. this.currentLayer.uvs[ name ] = {
  1306. uvIndices: uvIndices,
  1307. uvs: uvs,
  1308. };
  1309. }
  1310. },
  1311. parseMorphTargets( name, finalOffset, type ) {
  1312. var indices = [];
  1313. var points = [];
  1314. type = ( type === 'MORF' ) ? 'relative' : 'absolute';
  1315. while ( this.reader.offset < finalOffset ) {
  1316. indices.push( this.reader.getVariableLengthIndex() );
  1317. // z -> -z to match three.js right handed coords
  1318. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  1319. }
  1320. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  1321. this.currentLayer.morphTargets[ name ] = {
  1322. indices: indices,
  1323. points: points,
  1324. type: type,
  1325. };
  1326. },
  1327. // A list of polygons for the current layer.
  1328. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  1329. parsePolygonList( length ) {
  1330. var finalOffset = this.reader.offset + length;
  1331. var type = this.reader.getIDTag();
  1332. var indices = [];
  1333. // hold a list of polygon sizes, to be split up later
  1334. var polygonDimensions = [];
  1335. while ( this.reader.offset < finalOffset ) {
  1336. var numverts = this.reader.getUint16();
  1337. //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  1338. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  1339. polygonDimensions.push( numverts );
  1340. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  1341. }
  1342. var geometryData = {
  1343. type: type,
  1344. vertexIndices: indices,
  1345. polygonDimensions: polygonDimensions,
  1346. points: this.currentPoints
  1347. };
  1348. // Note: assuming that all polys will be lines or points if the first is
  1349. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
  1350. else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  1351. this.currentLayer.geometry = geometryData;
  1352. },
  1353. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  1354. // TAGS { tag-string[S0] * }
  1355. parseTagStrings( length ) {
  1356. this.tree.tags = this.reader.getStringArray( length );
  1357. },
  1358. // Associates tags of a given type with polygons in the most recent POLS chunk.
  1359. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  1360. parsePolygonTagMapping( length ) {
  1361. var finalOffset = this.reader.offset + length;
  1362. var type = this.reader.getIDTag();
  1363. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
  1364. else { //PART, SMGP, COLR not supported
  1365. this.reader.skip( length - 4 );
  1366. }
  1367. },
  1368. parseMaterialIndices( finalOffset ) {
  1369. // array holds polygon index followed by material index
  1370. this.currentLayer.geometry.materialIndices = [];
  1371. var initialMatIndex;
  1372. while ( this.reader.offset < finalOffset ) {
  1373. var polygonIndex = this.reader.getVariableLengthIndex();
  1374. var materialIndex = this.reader.getUint16();
  1375. if ( ! initialMatIndex ) initialMatIndex = materialIndex; // set up first mat index
  1376. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  1377. }
  1378. },
  1379. parseUnknownCHUNK( blockID, length ) {
  1380. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );
  1381. // print the chunk plus some bytes padding either side
  1382. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  1383. var data = this.reader.getString( length );
  1384. this.currentForm[ blockID ] = data;
  1385. }
  1386. };
  1387. function DataViewReader( buffer ) {
  1388. // For testing: dump whole buffer to console as a string
  1389. // printBuffer( buffer, 0, buffer.byteLength );
  1390. this.dv = new DataView( buffer );
  1391. this.offset = 0;
  1392. }
  1393. DataViewReader.prototype = {
  1394. constructor: DataViewReader,
  1395. size: function () {
  1396. return this.dv.buffer.byteLength;
  1397. },
  1398. setOffset( offset ) {
  1399. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  1400. this.offset = offset;
  1401. } else {
  1402. console.error( 'LWOLoader: invalid buffer offset' );
  1403. }
  1404. },
  1405. endOfFile: function () {
  1406. if ( this.offset >= this.size() ) return true;
  1407. return false;
  1408. },
  1409. skip: function ( length ) {
  1410. this.offset += length;
  1411. },
  1412. getUint8: function () {
  1413. var value = this.dv.getUint8( this.offset );
  1414. this.offset += 1;
  1415. return value;
  1416. },
  1417. getUint16: function () {
  1418. var value = this.dv.getUint16( this.offset );
  1419. this.offset += 2;
  1420. return value;
  1421. },
  1422. getInt32: function () {
  1423. var value = this.dv.getInt32( this.offset, false );
  1424. this.offset += 4;
  1425. return value;
  1426. },
  1427. getUint32: function () {
  1428. var value = this.dv.getUint32( this.offset, false );
  1429. this.offset += 4;
  1430. return value;
  1431. },
  1432. getUint64: function () {
  1433. var low, high;
  1434. high = this.getUint32();
  1435. low = this.getUint32();
  1436. return high * 0x100000000 + low;
  1437. },
  1438. getFloat32: function () {
  1439. var value = this.dv.getFloat32( this.offset, false );
  1440. this.offset += 4;
  1441. return value;
  1442. },
  1443. getFloat32Array: function ( size ) {
  1444. var a = [];
  1445. for ( var i = 0; i < size; i ++ ) {
  1446. a.push( this.getFloat32() );
  1447. }
  1448. return a;
  1449. },
  1450. getFloat64: function () {
  1451. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  1452. this.offset += 8;
  1453. return value;
  1454. },
  1455. getFloat64Array: function ( size ) {
  1456. var a = [];
  1457. for ( var i = 0; i < size; i ++ ) {
  1458. a.push( this.getFloat64() );
  1459. }
  1460. return a;
  1461. },
  1462. // get variable-length index data type
  1463. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  1464. // If the index value is less than 65,280 (0xFF00),then VX === U2
  1465. // otherwise VX === U4 with bits 24-31 set
  1466. // When reading an index, if the first byte encountered is 255 (0xFF), then
  1467. // the four-byte form is being used and the first byte should be discarded or masked out.
  1468. getVariableLengthIndex() {
  1469. var firstByte = this.getUint8();
  1470. if ( firstByte === 255 ) {
  1471. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  1472. }
  1473. return firstByte * 256 + this.getUint8();
  1474. },
  1475. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  1476. getIDTag() {
  1477. return this.getString( 4 );
  1478. },
  1479. getString: function ( size ) {
  1480. if ( size === 0 ) return;
  1481. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  1482. var a = [];
  1483. if ( size ) {
  1484. for ( var i = 0; i < size; i ++ ) {
  1485. a[ i ] = this.getUint8();
  1486. }
  1487. } else {
  1488. var currentChar;
  1489. var len = 0;
  1490. while ( currentChar !== 0 ) {
  1491. currentChar = this.getUint8();
  1492. if ( currentChar !== 0 ) a.push( currentChar );
  1493. len ++;
  1494. }
  1495. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  1496. }
  1497. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  1498. },
  1499. getStringArray: function ( size ) {
  1500. var a = this.getString( size );
  1501. a = a.split( '\0' );
  1502. return a.filter( Boolean ); // return array with any empty strings removed
  1503. }
  1504. };
  1505. // ************** UTILITY FUNCTIONS **************
  1506. function isEven( num ) {
  1507. return num % 2;
  1508. }
  1509. // calculate the length of the string in the buffer
  1510. // this will be string.length + nullbyte + optional padbyte to make the length even
  1511. function stringOffset( string ) {
  1512. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  1513. }
  1514. // for testing purposes, dump buffer to console
  1515. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  1516. function printBuffer( buffer, from, to ) {
  1517. console.log( THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  1518. }
  1519. return LWOLoader;
  1520. } )();