LWOLoader.js 67 KB

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