2
0

LWOLoader.js 53 KB

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