IFFParser.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /**
  2. * @author Lewy Blue / https://github.com/looeee
  3. * @author Guilherme Avila / https://github/sciecode
  4. *
  5. * === IFFParser ===
  6. * - Parses data from the IFF buffer.
  7. * - LWO3 files are in IFF format and can contain the following data types, referred to by shorthand codes
  8. *
  9. * ATOMIC DATA TYPES
  10. * ID Tag - 4x 7 bit uppercase ASCII chars: ID4
  11. * signed integer, 1, 2, or 4 byte length: I1, I2, I4
  12. * unsigned integer, 1, 2, or 4 byte length: U1, U2, U4
  13. * float, 4 byte length: F4
  14. * 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
  15. *
  16. * COMPOUND DATA TYPES
  17. * Variable-length Index (index into an array or collection): U2 or U4 : VX
  18. * Color (RGB): F4 + F4 + F4: COL12
  19. * Coordinate (x, y, z): F4 + F4 + F4: VEC12
  20. * Percentage F4 data type from 0->1 with 1 = 100%: FP4
  21. * Angle in radian F4: ANG4
  22. * Filename (string) S0: FNAM0
  23. * XValue F4 + index (VX) + optional envelope( ENVL ): XVAL
  24. * XValue vector VEC12 + index (VX) + optional envelope( ENVL ): XVAL3
  25. *
  26. * The IFF file is arranged in chunks:
  27. * CHUNK = ID4 + length (U4) + length X bytes of data + optional 0 pad byte
  28. * optional 0 pad byte is there to ensure chunk ends on even boundary, not counted in size
  29. *
  30. * COMPOUND DATA TYPES
  31. * - Chunks are combined in Forms (collections of chunks)
  32. * - FORM = string 'FORM' (ID4) + length (U4) + type (ID4) + optional ( CHUNK | FORM )
  33. * - CHUNKS and FORMS are collectively referred to as blocks
  34. * - The entire file is contained in one top level FORM
  35. *
  36. **/
  37. import { LoaderUtils } from "../../../../build/three.module.js";
  38. import { LWO2Parser } from "./LWO2Parser.js";
  39. import { LWO3Parser } from "./LWO3Parser.js";
  40. function IFFParser( ) {
  41. this.debugger = new Debugger();
  42. // this.debugger.enable(); // un-comment to log IFF hierarchy.
  43. }
  44. IFFParser.prototype = {
  45. constructor: IFFParser,
  46. parse: function ( buffer ) {
  47. this.reader = new DataViewReader( buffer );
  48. this.tree = {
  49. materials: {},
  50. layers: [],
  51. tags: [],
  52. textures: [],
  53. };
  54. // start out at the top level to add any data before first layer is encountered
  55. this.currentLayer = this.tree;
  56. this.currentForm = this.tree;
  57. this.parseTopForm();
  58. if ( this.tree.format === undefined ) return;
  59. if ( this.tree.format === 'LWO2' ) {
  60. this.parser = new LWO2Parser( this );
  61. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  62. } else if ( this.tree.format === 'LWO3' ) {
  63. this.parser = new LWO3Parser( this );
  64. while ( ! this.reader.endOfFile() ) this.parser.parseBlock();
  65. }
  66. this.debugger.offset = this.reader.offset;
  67. this.debugger.closeForms();
  68. return this.tree;
  69. },
  70. parseTopForm() {
  71. this.debugger.offset = this.reader.offset;
  72. var topForm = this.reader.getIDTag();
  73. if ( topForm !== 'FORM' ) {
  74. console.warn( "LWOLoader: Top-level FORM missing." );
  75. return;
  76. }
  77. var length = this.reader.getUint32();
  78. this.debugger.dataOffset = this.reader.offset;
  79. this.debugger.length = length;
  80. var type = this.reader.getIDTag();
  81. if ( type === 'LWO2' ) {
  82. this.tree.format = type;
  83. } else if ( type === 'LWO3' ) {
  84. this.tree.format = type;
  85. }
  86. this.debugger.node = 0;
  87. this.debugger.nodeID = type;
  88. this.debugger.log();
  89. return;
  90. },
  91. ///
  92. // FORM PARSING METHODS
  93. ///
  94. // Forms are organisational and can contain any number of sub chunks and sub forms
  95. // FORM ::= 'FORM'[ID4], length[U4], type[ID4], ( chunk[CHUNK] | form[FORM] ) * }
  96. parseForm( length ) {
  97. var type = this.reader.getIDTag();
  98. switch ( type ) {
  99. // SKIPPED FORMS
  100. // if skipForm( length ) is called, the entire form and any sub forms and chunks are skipped
  101. case 'ISEQ': // Image sequence
  102. case 'ANIM': // plug in animation
  103. case 'STCC': // Color-cycling Still
  104. case 'VPVL':
  105. case 'VPRM':
  106. case 'NROT':
  107. case 'WRPW': // image wrap w ( for cylindrical and spherical projections)
  108. case 'WRPH': // image wrap h
  109. case 'FUNC':
  110. case 'FALL':
  111. case 'OPAC':
  112. case 'GRAD': // gradient texture
  113. case 'ENVS':
  114. case 'VMOP':
  115. case 'VMBG':
  116. // Car Material FORMS
  117. case 'OMAX':
  118. case 'STEX':
  119. case 'CKBG':
  120. case 'CKEY':
  121. case 'VMLA':
  122. case 'VMLB':
  123. this.debugger.skipped = true;
  124. this.skipForm( length ); // not currently supported
  125. break;
  126. // if break; is called directly, the position in the lwoTree is not created
  127. // any sub chunks and forms are added to the parent form instead
  128. case 'META':
  129. case 'NNDS':
  130. case 'NODS':
  131. case 'NDTA':
  132. case 'ADAT':
  133. case 'AOVS':
  134. case 'BLOK':
  135. // used by texture nodes
  136. case 'IBGC': // imageBackgroundColor
  137. case 'IOPC': // imageOpacity
  138. case 'IIMG': // hold reference to image path
  139. case 'TXTR':
  140. // this.setupForm( type, length );
  141. this.debugger.length = 4;
  142. this.debugger.skipped = true;
  143. break;
  144. case 'IFAL': // imageFallof
  145. case 'ISCL': // imageScale
  146. case 'IPOS': // imagePosition
  147. case 'IROT': // imageRotation
  148. case 'IBMP':
  149. case 'IUTD':
  150. case 'IVTD':
  151. this.parseTextureNodeAttribute( type );
  152. break;
  153. case 'ENVL':
  154. this.parseEnvelope( length );
  155. break;
  156. // CLIP FORM AND SUB FORMS
  157. case 'CLIP':
  158. if ( this.tree.format === 'LWO2' ) {
  159. this.parseForm( length );
  160. } else {
  161. this.parseClip( length );
  162. }
  163. break;
  164. case 'STIL':
  165. this.parseImage();
  166. break;
  167. case 'XREF': // clone of another STIL
  168. this.reader.skip( 8 ); // unknown
  169. this.currentForm.referenceTexture = {
  170. index: this.reader.getUint32(),
  171. refName: this.reader.getString() // internal unique ref
  172. };
  173. break;
  174. // Not in spec, used by texture nodes
  175. case 'IMST':
  176. this.parseImageStateForm( length );
  177. break;
  178. // SURF FORM AND SUB FORMS
  179. case 'SURF':
  180. this.parseSurfaceForm( length );
  181. break;
  182. case 'VALU': // Not in spec
  183. this.parseValueForm( length );
  184. break;
  185. case 'NTAG':
  186. this.parseSubNode( length );
  187. break;
  188. case 'ATTR': // BSDF Node Attributes
  189. case 'SATR': // Standard Node Attributes
  190. this.setupForm( 'attributes', length );
  191. break;
  192. case 'NCON':
  193. this.parseConnections( length );
  194. break;
  195. case 'SSHA':
  196. this.parentForm = this.currentForm;
  197. this.currentForm = this.currentSurface;
  198. this.setupForm( 'surfaceShader', length );
  199. break;
  200. case 'SSHD':
  201. this.setupForm( 'surfaceShaderData', length );
  202. break;
  203. case 'ENTR': // Not in spec
  204. this.parseEntryForm( length );
  205. break;
  206. // Image Map Layer
  207. case 'IMAP':
  208. this.parseImageMap( length );
  209. break;
  210. case 'TAMP':
  211. this.parseXVAL( 'amplitude', length );
  212. break;
  213. //Texture Mapping Form
  214. case 'TMAP':
  215. this.setupForm( 'textureMap', length );
  216. break;
  217. case 'CNTR':
  218. this.parseXVAL3( 'center', length );
  219. break;
  220. case 'SIZE':
  221. this.parseXVAL3( 'scale', length );
  222. break;
  223. case 'ROTA':
  224. this.parseXVAL3( 'rotation', length );
  225. break;
  226. default:
  227. this.parseUnknownForm( type, length );
  228. }
  229. this.debugger.node = 0;
  230. this.debugger.nodeID = type;
  231. this.debugger.log();
  232. },
  233. setupForm( type, length ) {
  234. if ( ! this.currentForm ) this.currentForm = this.currentNode;
  235. this.currentFormEnd = this.reader.offset + length;
  236. this.parentForm = this.currentForm;
  237. if ( ! this.currentForm[ type ] ) {
  238. this.currentForm[ type ] = {};
  239. this.currentForm = this.currentForm[ type ];
  240. } else {
  241. // should never see this unless there's a bug in the reader
  242. console.warn( 'LWOLoader: form already exists on parent: ', type, this.currentForm );
  243. this.currentForm = this.currentForm[ type ];
  244. }
  245. },
  246. skipForm( length ) {
  247. this.reader.skip( length - 4 );
  248. },
  249. parseUnknownForm( type, length ) {
  250. console.warn( 'LWOLoader: unknown FORM encountered: ' + type, length );
  251. printBuffer( this.reader.dv.buffer, this.reader.offset, length - 4 );
  252. this.reader.skip( length - 4 );
  253. },
  254. parseSurfaceForm( length ) {
  255. this.reader.skip( 8 ); // unknown Uint32 x2
  256. var name = this.reader.getString();
  257. var surface = {
  258. attributes: {}, // LWO2 style non-node attributes will go here
  259. connections: {},
  260. name: name,
  261. inputName: name,
  262. nodes: {},
  263. source: this.reader.getString(),
  264. };
  265. this.tree.materials[ name ] = surface;
  266. this.currentSurface = surface;
  267. this.parentForm = this.tree.materials;
  268. this.currentForm = surface;
  269. this.currentFormEnd = this.reader.offset + length;
  270. },
  271. parseSurfaceLwo2( length ) {
  272. var name = this.reader.getString();
  273. var surface = {
  274. attributes: {}, // LWO2 style non-node attributes will go here
  275. connections: {},
  276. name: name,
  277. nodes: {},
  278. source: this.reader.getString(),
  279. };
  280. this.tree.materials[ name ] = surface;
  281. this.currentSurface = surface;
  282. this.parentForm = this.tree.materials;
  283. this.currentForm = surface;
  284. this.currentFormEnd = this.reader.offset + length;
  285. },
  286. parseSubNode( length ) {
  287. // parse the NRNM CHUNK of the subnode FORM to get
  288. // a meaningful name for the subNode
  289. // some subnodes can be renamed, but Input and Surface cannot
  290. this.reader.skip( 8 ); // NRNM + length
  291. var name = this.reader.getString();
  292. var node = {
  293. name: name
  294. };
  295. this.currentForm = node;
  296. this.currentNode = node;
  297. this.currentFormEnd = this.reader.offset + length;
  298. },
  299. // collect attributes from all nodes at the top level of a surface
  300. parseConnections( length ) {
  301. this.currentFormEnd = this.reader.offset + length;
  302. this.parentForm = this.currentForm;
  303. this.currentForm = this.currentSurface.connections;
  304. },
  305. // surface node attribute data, e.g. specular, roughness etc
  306. parseEntryForm( length ) {
  307. this.reader.skip( 8 ); // NAME + length
  308. var name = this.reader.getString();
  309. this.currentForm = this.currentNode.attributes;
  310. this.setupForm( name, length );
  311. },
  312. // parse values from material - doesn't match up to other LWO3 data types
  313. // sub form of entry form
  314. parseValueForm() {
  315. this.reader.skip( 8 ); // unknown + length
  316. var valueType = this.reader.getString();
  317. if ( valueType === 'double' ) {
  318. this.currentForm.value = this.reader.getUint64();
  319. } else if ( valueType === 'int' ) {
  320. this.currentForm.value = this.reader.getUint32();
  321. } else if ( valueType === 'vparam' ) {
  322. this.reader.skip( 24 );
  323. this.currentForm.value = this.reader.getFloat64();
  324. } else if ( valueType === 'vparam3' ) {
  325. this.reader.skip( 24 );
  326. this.currentForm.value = this.reader.getFloat64Array( 3 );
  327. }
  328. },
  329. // holds various data about texture node image state
  330. // Data other thanmipMapLevel unknown
  331. parseImageStateForm() {
  332. this.reader.skip( 8 ); // unknown
  333. this.currentForm.mipMapLevel = this.reader.getFloat32();
  334. },
  335. // LWO2 style image data node OR LWO3 textures defined at top level in editor (not as SURF node)
  336. parseImageMap( length ) {
  337. this.currentFormEnd = this.reader.offset + length;
  338. this.parentForm = this.currentForm;
  339. if ( ! this.currentForm.maps ) this.currentForm.maps = [];
  340. var map = {};
  341. this.currentForm.maps.push( map );
  342. this.currentForm = map;
  343. this.reader.skip( 10 ); // unknown, could be an issue if it contains a VX
  344. },
  345. parseTextureNodeAttribute( type ) {
  346. this.reader.skip( 28 ); // FORM + length + VPRM + unknown + Uint32 x2 + float32
  347. this.reader.skip( 20 ); // FORM + length + VPVL + float32 + Uint32
  348. switch ( type ) {
  349. case 'ISCL':
  350. this.currentNode.scale = this.reader.getFloat32Array( 3 );
  351. break;
  352. case 'IPOS':
  353. this.currentNode.position = this.reader.getFloat32Array( 3 );
  354. break;
  355. case 'IROT':
  356. this.currentNode.rotation = this.reader.getFloat32Array( 3 );
  357. break;
  358. case 'IFAL':
  359. this.currentNode.falloff = this.reader.getFloat32Array( 3 );
  360. break;
  361. case 'IBMP':
  362. this.currentNode.amplitude = this.reader.getFloat32();
  363. break;
  364. case 'IUTD':
  365. this.currentNode.uTiles = this.reader.getFloat32();
  366. break;
  367. case 'IVTD':
  368. this.currentNode.vTiles = this.reader.getFloat32();
  369. break;
  370. }
  371. this.reader.skip( 2 ); // unknown
  372. },
  373. // ENVL forms are currently ignored
  374. parseEnvelope( length ) {
  375. this.reader.skip( length - 4 ); // skipping entirely for now
  376. },
  377. ///
  378. // CHUNK PARSING METHODS
  379. ///
  380. // clips can either be defined inside a surface node, or at the top
  381. // level and they have a different format in each case
  382. parseClip( length ) {
  383. var tag = this.reader.getIDTag();
  384. // inside surface node
  385. if ( tag === 'FORM' ) {
  386. this.reader.skip( 16 );
  387. this.currentNode.fileName = this.reader.getString();
  388. return;
  389. }
  390. // otherwise top level
  391. this.reader.setOffset( this.reader.offset - 4 );
  392. this.currentFormEnd = this.reader.offset + length;
  393. this.parentForm = this.currentForm;
  394. this.reader.skip( 8 ); // unknown
  395. var texture = {
  396. index: this.reader.getUint32()
  397. };
  398. this.tree.textures.push( texture );
  399. this.currentForm = texture;
  400. },
  401. parseClipLwo2( length ) {
  402. var texture = {
  403. index: this.reader.getUint32(),
  404. fileName: ""
  405. };
  406. // seach STIL block
  407. while ( true ) {
  408. var tag = this.reader.getIDTag();
  409. var n_length = this.reader.getUint16();
  410. if ( tag === 'STIL' ) {
  411. texture.fileName = this.reader.getString();
  412. break;
  413. }
  414. if ( n_length >= length ) {
  415. break;
  416. }
  417. }
  418. this.tree.textures.push( texture );
  419. this.currentForm = texture;
  420. },
  421. parseImage() {
  422. this.reader.skip( 8 ); // unknown
  423. this.currentForm.fileName = this.reader.getString();
  424. },
  425. parseXVAL( type, length ) {
  426. var endOffset = this.reader.offset + length - 4;
  427. this.reader.skip( 8 );
  428. this.currentForm[ type ] = this.reader.getFloat32();
  429. this.reader.setOffset( endOffset ); // set end offset directly to skip optional envelope
  430. },
  431. parseXVAL3( type, length ) {
  432. var endOffset = this.reader.offset + length - 4;
  433. this.reader.skip( 8 );
  434. this.currentForm[ type ] = {
  435. x: this.reader.getFloat32(),
  436. y: this.reader.getFloat32(),
  437. z: this.reader.getFloat32(),
  438. };
  439. this.reader.setOffset( endOffset );
  440. },
  441. // Tags associated with an object
  442. // OTAG { type[ID4], tag-string[S0] }
  443. parseObjectTag() {
  444. if ( ! this.tree.objectTags ) this.tree.objectTags = {};
  445. this.tree.objectTags[ this.reader.getIDTag() ] = {
  446. tagString: this.reader.getString()
  447. };
  448. },
  449. // 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.
  450. // LAYR: number[U2], flags[U2], pivot[VEC12], name[S0], parent[U2]
  451. parseLayer( length ) {
  452. var layer = {
  453. number: this.reader.getUint16(),
  454. flags: this.reader.getUint16(), // If the least significant bit of flags is set, the layer is hidden.
  455. pivot: this.reader.getFloat32Array( 3 ), // Note: this seems to be superflous, as the geometry is translated when pivot is present
  456. name: this.reader.getString(),
  457. };
  458. this.tree.layers.push( layer );
  459. this.currentLayer = layer;
  460. var parsedLength = 16 + stringOffset( this.currentLayer.name ); // index ( 2 ) + flags( 2 ) + pivot( 12 ) + stringlength
  461. // if we have not reached then end of the layer block, there must be a parent defined
  462. this.currentLayer.parent = ( parsedLength < length ) ? this.reader.getUint16() : - 1; // omitted or -1 for no parent
  463. },
  464. // VEC12 * ( F4 + F4 + F4 ) array of x,y,z vectors
  465. // Converting from left to right handed coordinate system:
  466. // x -> -x and switch material FrontSide -> BackSide
  467. parsePoints( length ) {
  468. this.currentPoints = [];
  469. for ( var i = 0; i < length / 4; i += 3 ) {
  470. // z -> -z to match three.js right handed coords
  471. this.currentPoints.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  472. }
  473. },
  474. // parse VMAP or VMAD
  475. // Associates a set of floating-point vectors with a set of points.
  476. // VMAP: { type[ID4], dimension[U2], name[S0], ( vert[VX], value[F4] # dimension ) * }
  477. // VMAD Associates a set of floating-point vectors with the vertices of specific polygons.
  478. // Similar to VMAP UVs, but associates with polygon vertices rather than points
  479. // to solve to problem of UV seams: VMAD chunks are paired with VMAPs of the same name,
  480. // if they exist. The vector values in the VMAD will then replace those in the
  481. // corresponding VMAP, but only for calculations involving the specified polygons.
  482. // VMAD { type[ID4], dimension[U2], name[S0], ( vert[VX], poly[VX], value[F4] # dimension ) * }
  483. parseVertexMapping( length, discontinuous ) {
  484. var finalOffset = this.reader.offset + length;
  485. var channelName = this.reader.getString();
  486. if ( this.reader.offset === finalOffset ) {
  487. // then we are in a texture node and the VMAP chunk is just a reference to a UV channel name
  488. this.currentForm.UVChannel = channelName;
  489. return;
  490. }
  491. // otherwise reset to initial length and parse normal VMAP CHUNK
  492. this.reader.setOffset( this.reader.offset - stringOffset( channelName ) );
  493. var type = this.reader.getIDTag();
  494. this.reader.getUint16(); // dimension
  495. var name = this.reader.getString();
  496. var remainingLength = length - 6 - stringOffset( name );
  497. switch ( type ) {
  498. case 'TXUV':
  499. this.parseUVMapping( name, finalOffset, discontinuous );
  500. break;
  501. case 'MORF':
  502. case 'SPOT':
  503. this.parseMorphTargets( name, finalOffset, type ); // can't be discontinuous
  504. break;
  505. // unsupported VMAPs
  506. case 'APSL':
  507. case 'NORM':
  508. case 'WGHT':
  509. case 'MNVW':
  510. case 'PICK':
  511. case 'RGB ':
  512. case 'RGBA':
  513. this.reader.skip( remainingLength );
  514. break;
  515. default:
  516. console.warn( 'LWOLoader: unknown vertex map type: ' + type );
  517. this.reader.skip( remainingLength );
  518. }
  519. },
  520. parseUVMapping( name, finalOffset, discontinuous ) {
  521. var uvIndices = [];
  522. var polyIndices = [];
  523. var uvs = [];
  524. while ( this.reader.offset < finalOffset ) {
  525. uvIndices.push( this.reader.getVariableLengthIndex() );
  526. if ( discontinuous ) polyIndices.push( this.reader.getVariableLengthIndex() );
  527. uvs.push( this.reader.getFloat32(), this.reader.getFloat32() );
  528. }
  529. if ( discontinuous ) {
  530. if ( ! this.currentLayer.discontinuousUVs ) this.currentLayer.discontinuousUVs = {};
  531. this.currentLayer.discontinuousUVs[ name ] = {
  532. uvIndices: uvIndices,
  533. polyIndices: polyIndices,
  534. uvs: uvs,
  535. };
  536. } else {
  537. if ( ! this.currentLayer.uvs ) this.currentLayer.uvs = {};
  538. this.currentLayer.uvs[ name ] = {
  539. uvIndices: uvIndices,
  540. uvs: uvs,
  541. };
  542. }
  543. },
  544. parseMorphTargets( name, finalOffset, type ) {
  545. var indices = [];
  546. var points = [];
  547. type = ( type === 'MORF' ) ? 'relative' : 'absolute';
  548. while ( this.reader.offset < finalOffset ) {
  549. indices.push( this.reader.getVariableLengthIndex() );
  550. // z -> -z to match three.js right handed coords
  551. points.push( this.reader.getFloat32(), this.reader.getFloat32(), - this.reader.getFloat32() );
  552. }
  553. if ( ! this.currentLayer.morphTargets ) this.currentLayer.morphTargets = {};
  554. this.currentLayer.morphTargets[ name ] = {
  555. indices: indices,
  556. points: points,
  557. type: type,
  558. };
  559. },
  560. // A list of polygons for the current layer.
  561. // POLS { type[ID4], ( numvert+flags[U2], vert[VX] # numvert ) * }
  562. parsePolygonList( length ) {
  563. var finalOffset = this.reader.offset + length;
  564. var type = this.reader.getIDTag();
  565. var indices = [];
  566. // hold a list of polygon sizes, to be split up later
  567. var polygonDimensions = [];
  568. while ( this.reader.offset < finalOffset ) {
  569. var numverts = this.reader.getUint16();
  570. //var flags = numverts & 64512; // 6 high order bits are flags - ignoring for now
  571. numverts = numverts & 1023; // remaining ten low order bits are vertex num
  572. polygonDimensions.push( numverts );
  573. for ( var j = 0; j < numverts; j ++ ) indices.push( this.reader.getVariableLengthIndex() );
  574. }
  575. var geometryData = {
  576. type: type,
  577. vertexIndices: indices,
  578. polygonDimensions: polygonDimensions,
  579. points: this.currentPoints
  580. };
  581. // Note: assuming that all polys will be lines or points if the first is
  582. if ( polygonDimensions[ 0 ] === 1 ) geometryData.type = 'points';
  583. else if ( polygonDimensions[ 0 ] === 2 ) geometryData.type = 'lines';
  584. this.currentLayer.geometry = geometryData;
  585. },
  586. // Lists the tag strings that can be associated with polygons by the PTAG chunk.
  587. // TAGS { tag-string[S0] * }
  588. parseTagStrings( length ) {
  589. this.tree.tags = this.reader.getStringArray( length );
  590. },
  591. // Associates tags of a given type with polygons in the most recent POLS chunk.
  592. // PTAG { type[ID4], ( poly[VX], tag[U2] ) * }
  593. parsePolygonTagMapping( length ) {
  594. var finalOffset = this.reader.offset + length;
  595. var type = this.reader.getIDTag();
  596. if ( type === 'SURF' ) this.parseMaterialIndices( finalOffset );
  597. else { //PART, SMGP, COLR not supported
  598. this.reader.skip( length - 4 );
  599. }
  600. },
  601. parseMaterialIndices( finalOffset ) {
  602. // array holds polygon index followed by material index
  603. this.currentLayer.geometry.materialIndices = [];
  604. while ( this.reader.offset < finalOffset ) {
  605. var polygonIndex = this.reader.getVariableLengthIndex();
  606. var materialIndex = this.reader.getUint16();
  607. this.currentLayer.geometry.materialIndices.push( polygonIndex, materialIndex );
  608. }
  609. },
  610. parseUnknownCHUNK( blockID, length ) {
  611. console.warn( 'LWOLoader: unknown chunk type: ' + blockID + ' length: ' + length );
  612. // print the chunk plus some bytes padding either side
  613. // printBuffer( this.reader.dv.buffer, this.reader.offset - 20, length + 40 );
  614. var data = this.reader.getString( length );
  615. this.currentForm[ blockID ] = data;
  616. }
  617. };
  618. function DataViewReader( buffer ) {
  619. this.dv = new DataView( buffer );
  620. this.offset = 0;
  621. }
  622. DataViewReader.prototype = {
  623. constructor: DataViewReader,
  624. size: function () {
  625. return this.dv.buffer.byteLength;
  626. },
  627. setOffset( offset ) {
  628. if ( offset > 0 && offset < this.dv.buffer.byteLength ) {
  629. this.offset = offset;
  630. } else {
  631. console.error( 'LWOLoader: invalid buffer offset' );
  632. }
  633. },
  634. endOfFile: function () {
  635. if ( this.offset >= this.size() ) return true;
  636. return false;
  637. },
  638. skip: function ( length ) {
  639. this.offset += length;
  640. },
  641. getUint8: function () {
  642. var value = this.dv.getUint8( this.offset );
  643. this.offset += 1;
  644. return value;
  645. },
  646. getUint16: function () {
  647. var value = this.dv.getUint16( this.offset );
  648. this.offset += 2;
  649. return value;
  650. },
  651. getInt32: function () {
  652. var value = this.dv.getInt32( this.offset, false );
  653. this.offset += 4;
  654. return value;
  655. },
  656. getUint32: function () {
  657. var value = this.dv.getUint32( this.offset, false );
  658. this.offset += 4;
  659. return value;
  660. },
  661. getUint64: function () {
  662. var low, high;
  663. high = this.getUint32();
  664. low = this.getUint32();
  665. return high * 0x100000000 + low;
  666. },
  667. getFloat32: function () {
  668. var value = this.dv.getFloat32( this.offset, false );
  669. this.offset += 4;
  670. return value;
  671. },
  672. getFloat32Array: function ( size ) {
  673. var a = [];
  674. for ( var i = 0; i < size; i ++ ) {
  675. a.push( this.getFloat32() );
  676. }
  677. return a;
  678. },
  679. getFloat64: function () {
  680. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  681. this.offset += 8;
  682. return value;
  683. },
  684. getFloat64Array: function ( size ) {
  685. var a = [];
  686. for ( var i = 0; i < size; i ++ ) {
  687. a.push( this.getFloat64() );
  688. }
  689. return a;
  690. },
  691. // get variable-length index data type
  692. // VX ::= index[U2] | (index + 0xFF000000)[U4]
  693. // If the index value is less than 65,280 (0xFF00),then VX === U2
  694. // otherwise VX === U4 with bits 24-31 set
  695. // When reading an index, if the first byte encountered is 255 (0xFF), then
  696. // the four-byte form is being used and the first byte should be discarded or masked out.
  697. getVariableLengthIndex() {
  698. var firstByte = this.getUint8();
  699. if ( firstByte === 255 ) {
  700. return this.getUint8() * 65536 + this.getUint8() * 256 + this.getUint8();
  701. }
  702. return firstByte * 256 + this.getUint8();
  703. },
  704. // An ID tag is a sequence of 4 bytes containing 7-bit ASCII values
  705. getIDTag() {
  706. return this.getString( 4 );
  707. },
  708. getString: function ( size ) {
  709. if ( size === 0 ) return;
  710. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  711. var a = [];
  712. if ( size ) {
  713. for ( var i = 0; i < size; i ++ ) {
  714. a[ i ] = this.getUint8();
  715. }
  716. } else {
  717. var currentChar;
  718. var len = 0;
  719. while ( currentChar !== 0 ) {
  720. currentChar = this.getUint8();
  721. if ( currentChar !== 0 ) a.push( currentChar );
  722. len ++;
  723. }
  724. if ( ! isEven( len + 1 ) ) this.getUint8(); // if string with terminating nullbyte is uneven, extra nullbyte is added
  725. }
  726. return LoaderUtils.decodeText( new Uint8Array( a ) );
  727. },
  728. getStringArray: function ( size ) {
  729. var a = this.getString( size );
  730. a = a.split( '\0' );
  731. return a.filter( Boolean ); // return array with any empty strings removed
  732. }
  733. };
  734. // ************** DEBUGGER **************
  735. function Debugger( ) {
  736. this.active = false;
  737. this.depth = 0;
  738. this.formList = [];
  739. }
  740. Debugger.prototype = {
  741. constructor: Debugger,
  742. enable: function () {
  743. this.active = true;
  744. },
  745. log: function () {
  746. if ( ! this.active ) return;
  747. var nodeType;
  748. switch ( this.node ) {
  749. case 0:
  750. nodeType = "FORM";
  751. break;
  752. case 1:
  753. nodeType = "CHK";
  754. break;
  755. case 2:
  756. nodeType = "S-CHK";
  757. break;
  758. }
  759. console.log(
  760. "| ".repeat( this.depth ) +
  761. nodeType,
  762. this.nodeID,
  763. `( ${this.offset} ) -> ( ${this.dataOffset + this.length} )`,
  764. ( ( this.node == 0 ) ? " {" : "" ),
  765. ( ( this.skipped ) ? "SKIPPED" : "" ),
  766. ( ( this.node == 0 && this.skipped ) ? "}" : "" )
  767. );
  768. if ( this.node == 0 && ! this.skipped ) {
  769. this.depth += 1;
  770. this.formList.push( this.dataOffset + this.length );
  771. }
  772. this.skipped = false;
  773. },
  774. closeForms: function () {
  775. if ( ! this.active ) return;
  776. for ( var i = this.formList.length - 1; i >= 0; i -- ) {
  777. if ( this.offset >= this.formList[ i ] ) {
  778. this.depth -= 1;
  779. console.log( "| ".repeat( this.depth ) + "}" );
  780. this.formList.splice( - 1, 1 );
  781. }
  782. }
  783. }
  784. };
  785. // ************** UTILITY FUNCTIONS **************
  786. function isEven( num ) {
  787. return num % 2;
  788. }
  789. // calculate the length of the string in the buffer
  790. // this will be string.length + nullbyte + optional padbyte to make the length even
  791. function stringOffset( string ) {
  792. return string.length + 1 + ( isEven( string.length + 1 ) ? 1 : 0 );
  793. }
  794. // for testing purposes, dump buffer to console
  795. // printBuffer( this.reader.dv.buffer, this.reader.offset, length );
  796. function printBuffer( buffer, from, to ) {
  797. console.log( LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) ) );
  798. }
  799. export { IFFParser };