IFFParser.js 26 KB

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