IFFParser.js 26 KB

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