LWOLoader.js 56 KB

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