VRMLLoader.js 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.VRMLLoader = function ( manager ) {
  5. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6. };
  7. THREE.VRMLLoader.prototype = {
  8. constructor: THREE.VRMLLoader,
  9. // for IndexedFaceSet support
  10. isRecordingPoints: false,
  11. isRecordingFaces: false,
  12. points: [],
  13. indexes : [],
  14. // for Background support
  15. isRecordingAngles: false,
  16. isRecordingColors: false,
  17. angles: [],
  18. colors: [],
  19. recordingFieldname: null,
  20. crossOrigin: 'Anonymous',
  21. load: function ( url, onLoad, onProgress, onError ) {
  22. var scope = this;
  23. var loader = new THREE.FileLoader( this.manager );
  24. loader.load( url, function ( text ) {
  25. onLoad( scope.parse( text ) );
  26. }, onProgress, onError );
  27. },
  28. setCrossOrigin: function ( value ) {
  29. this.crossOrigin = value;
  30. },
  31. parse: function ( data ) {
  32. var texturePath = this.texturePath || '';
  33. var textureLoader = new THREE.TextureLoader( this.manager );
  34. textureLoader.setCrossOrigin( this.crossOrigin );
  35. var parseV1 = function ( lines, scene ) {
  36. console.warn( 'VRML V1.0 not supported yet' );
  37. };
  38. var parseV2 = function ( lines, scene ) {
  39. var defines = {};
  40. var float_pattern = /(\b|\-|\+)([\d\.e]+)/;
  41. var float2_pattern = /([\d\.\+\-e]+)\s+([\d\.\+\-e]+)/g;
  42. var float3_pattern = /([\d\.\+\-e]+)\s+([\d\.\+\-e]+)\s+([\d\.\+\-e]+)/g;
  43. /**
  44. * Interpolates colors a and b following their relative distance
  45. * expressed by t.
  46. *
  47. * @param float a
  48. * @param float b
  49. * @param float t
  50. * @returns {Color}
  51. */
  52. var interpolateColors = function( a, b, t ) {
  53. var deltaR = a.r - b.r;
  54. var deltaG = a.g - b.g;
  55. var deltaB = a.b - b.b;
  56. var c = new THREE.Color();
  57. c.r = a.r - t * deltaR;
  58. c.g = a.g - t * deltaG;
  59. c.b = a.b - t * deltaB;
  60. return c;
  61. };
  62. /**
  63. * Vertically paints the faces interpolating between the
  64. * specified colors at the specified angels. This is used for the Background
  65. * node, but could be applied to other nodes with multiple faces as well.
  66. *
  67. * When used with the Background node, default is directionIsDown is true if
  68. * interpolating the skyColor down from the Zenith. When interpolationg up from
  69. * the Nadir i.e. interpolating the groundColor, the directionIsDown is false.
  70. *
  71. * The first angle is never specified, it is the Zenith (0 rad). Angles are specified
  72. * in radians. The geometry is thought a sphere, but could be anything. The color interpolation
  73. * is linear along the Y axis in any case.
  74. *
  75. * You must specify one more color than you have angles at the beginning of the colors array.
  76. * This is the color of the Zenith (the top of the shape).
  77. *
  78. * @param geometry
  79. * @param radius
  80. * @param angles
  81. * @param colors
  82. * @param boolean directionIsDown Whether to work bottom up or top down.
  83. */
  84. var paintFaces = function ( geometry, radius, angles, colors, directionIsDown ) {
  85. var direction = directionIsDown ? 1 : - 1;
  86. var faceIndices = [ 'a', 'b', 'c', 'd' ];
  87. var coord = [], A = {}, B = {}, applyColor = false;
  88. for ( var k = 0; k < angles.length; k ++ ) {
  89. // push the vector at which the color changes
  90. var vec = {
  91. x: direction * ( Math.cos( angles[ k ] ) * radius ),
  92. y: direction * ( Math.sin( angles[ k ] ) * radius )
  93. };
  94. coord.push( vec );
  95. }
  96. // painting the colors on the faces
  97. for ( var i = 0; i < geometry.faces.length ; i ++ ) {
  98. var f = geometry.faces[ i ];
  99. var n = ( f instanceof THREE.Face3 ) ? 3 : 4;
  100. for ( var j = 0; j < n; j ++ ) {
  101. var vertexIndex = f[ faceIndices[ j ] ];
  102. var p = geometry.vertices[ vertexIndex ];
  103. for ( var index = 0; index < colors.length; index ++ ) {
  104. // linear interpolation between aColor and bColor, calculate proportion
  105. // A is previous point (angle)
  106. if ( index === 0 ) {
  107. A.x = 0;
  108. A.y = directionIsDown ? radius : - 1 * radius;
  109. } else {
  110. A.x = coord[ index - 1 ].x;
  111. A.y = coord[ index - 1 ].y;
  112. }
  113. // B is current point (angle)
  114. B = coord[ index ];
  115. if ( undefined !== B ) {
  116. // p has to be between the points A and B which we interpolate
  117. applyColor = directionIsDown ? p.y <= A.y && p.y > B.y : p.y >= A.y && p.y < B.y;
  118. if ( applyColor ) {
  119. var aColor = colors[ index ];
  120. var bColor = colors[ index + 1 ];
  121. // below is simple linear interpolation
  122. var t = Math.abs( p.y - A.y ) / ( A.y - B.y );
  123. // to make it faster, you can only calculate this if the y coord changes, the color is the same for points with the same y
  124. var color = interpolateColors( aColor, bColor, t );
  125. f.vertexColors[ j ] = color;
  126. }
  127. } else if ( undefined === f.vertexColors[ j ] ) {
  128. var colorIndex = directionIsDown ? colors.length - 1 : 0;
  129. f.vertexColors[ j ] = colors[ colorIndex ];
  130. }
  131. }
  132. }
  133. }
  134. };
  135. var index = [];
  136. var parseProperty = function ( node, line ) {
  137. var parts = [], part, property = {}, fieldName;
  138. /**
  139. * Expression for matching relevant information, such as a name or value, but not the separators
  140. * @type {RegExp}
  141. */
  142. var regex = /[^\s,\[\]]+/g;
  143. var point, angles, colors;
  144. while ( null != ( part = regex.exec( line ) ) ) {
  145. parts.push( part[ 0 ] );
  146. }
  147. fieldName = parts[ 0 ];
  148. // trigger several recorders
  149. switch ( fieldName ) {
  150. case 'skyAngle':
  151. case 'groundAngle':
  152. this.recordingFieldname = fieldName;
  153. this.isRecordingAngles = true;
  154. this.angles = [];
  155. break;
  156. case 'skyColor':
  157. case 'groundColor':
  158. this.recordingFieldname = fieldName;
  159. this.isRecordingColors = true;
  160. this.colors = [];
  161. break;
  162. case 'point':
  163. this.recordingFieldname = fieldName;
  164. this.isRecordingPoints = true;
  165. this.points = [];
  166. break;
  167. case 'coordIndex':
  168. case 'texCoordIndex':
  169. this.recordingFieldname = fieldName;
  170. this.isRecordingFaces = true;
  171. this.indexes = [];
  172. }
  173. if ( this.isRecordingFaces ) {
  174. // the parts hold the indexes as strings
  175. if ( parts.length > 0 ) {
  176. for ( var ind = 0; ind < parts.length; ind ++ ) {
  177. // the part should either be positive integer or -1
  178. if ( ! /(-?\d+)/.test( parts[ ind ] ) ) {
  179. continue;
  180. }
  181. // end of current face
  182. if ( parts[ ind ] === "-1" ) {
  183. if ( index.length > 0 ) {
  184. this.indexes.push( index );
  185. }
  186. // start new one
  187. index = [];
  188. } else {
  189. index.push( parseInt( parts[ ind ] ) );
  190. }
  191. }
  192. }
  193. // end
  194. if ( /]/.exec( line ) ) {
  195. if ( index.length > 0 ) {
  196. this.indexes.push( index );
  197. }
  198. // start new one
  199. index = [];
  200. this.isRecordingFaces = false;
  201. node[this.recordingFieldname] = this.indexes;
  202. }
  203. } else if ( this.isRecordingPoints ) {
  204. if ( node.nodeType == 'Coordinate' )
  205. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  206. point = {
  207. x: parseFloat( parts[ 1 ] ),
  208. y: parseFloat( parts[ 2 ] ),
  209. z: parseFloat( parts[ 3 ] )
  210. };
  211. this.points.push( point );
  212. }
  213. if ( node.nodeType == 'TextureCoordinate' )
  214. while ( null !== ( parts = float2_pattern.exec( line ) ) ) {
  215. point = {
  216. x: parseFloat( parts[ 1 ] ),
  217. y: parseFloat( parts[ 2 ] )
  218. };
  219. this.points.push( point );
  220. }
  221. // end
  222. if ( /]/.exec( line ) ) {
  223. this.isRecordingPoints = false;
  224. node.points = this.points;
  225. }
  226. } else if ( this.isRecordingAngles ) {
  227. // the parts hold the angles as strings
  228. if ( parts.length > 0 ) {
  229. for ( var ind = 0; ind < parts.length; ind ++ ) {
  230. // the part should be a float
  231. if ( ! float_pattern.test( parts[ ind ] ) ) {
  232. continue;
  233. }
  234. this.angles.push( parseFloat( parts[ ind ] ) );
  235. }
  236. }
  237. // end
  238. if ( /]/.exec( line ) ) {
  239. this.isRecordingAngles = false;
  240. node[ this.recordingFieldname ] = this.angles;
  241. }
  242. } else if ( this.isRecordingColors ) {
  243. while ( null !== ( parts = float3_pattern.exec( line ) ) ) {
  244. var color = {
  245. r: parseFloat( parts[ 1 ] ),
  246. g: parseFloat( parts[ 2 ] ),
  247. b: parseFloat( parts[ 3 ] )
  248. };
  249. this.colors.push( color );
  250. }
  251. // end
  252. if ( /]/.exec( line ) ) {
  253. this.isRecordingColors = false;
  254. node[ this.recordingFieldname ] = this.colors;
  255. }
  256. } else if ( parts[ parts.length - 1 ] !== 'NULL' && fieldName !== 'children' ) {
  257. switch ( fieldName ) {
  258. case 'diffuseColor':
  259. case 'emissiveColor':
  260. case 'specularColor':
  261. case 'color':
  262. if ( parts.length != 4 ) {
  263. console.warn( 'Invalid color format detected for ' + fieldName );
  264. break;
  265. }
  266. property = {
  267. r: parseFloat( parts[ 1 ] ),
  268. g: parseFloat( parts[ 2 ] ),
  269. b: parseFloat( parts[ 3 ] )
  270. };
  271. break;
  272. case 'location':
  273. case 'direction':
  274. case 'translation':
  275. case 'scale':
  276. case 'size':
  277. if ( parts.length != 4 ) {
  278. console.warn( 'Invalid vector format detected for ' + fieldName );
  279. break;
  280. }
  281. property = {
  282. x: parseFloat( parts[ 1 ] ),
  283. y: parseFloat( parts[ 2 ] ),
  284. z: parseFloat( parts[ 3 ] )
  285. };
  286. break;
  287. case 'intensity':
  288. case 'cutOffAngle':
  289. case 'radius':
  290. case 'topRadius':
  291. case 'bottomRadius':
  292. case 'height':
  293. case 'transparency':
  294. case 'shininess':
  295. case 'ambientIntensity':
  296. if ( parts.length != 2 ) {
  297. console.warn( 'Invalid single float value specification detected for ' + fieldName );
  298. break;
  299. }
  300. property = parseFloat( parts[ 1 ] );
  301. break;
  302. case 'rotation':
  303. if ( parts.length != 5 ) {
  304. console.warn( 'Invalid quaternion format detected for ' + fieldName );
  305. break;
  306. }
  307. property = {
  308. x: parseFloat( parts[ 1 ] ),
  309. y: parseFloat( parts[ 2 ] ),
  310. z: parseFloat( parts[ 3 ] ),
  311. w: parseFloat( parts[ 4 ] )
  312. };
  313. break;
  314. case 'on':
  315. case 'ccw':
  316. case 'solid':
  317. case 'colorPerVertex':
  318. case 'convex':
  319. if ( parts.length != 2 ) {
  320. console.warn( 'Invalid format detected for ' + fieldName );
  321. break;
  322. }
  323. property = parts[ 1 ] === 'TRUE' ? true : false;
  324. break;
  325. }
  326. node[ fieldName ] = property;
  327. }
  328. return property;
  329. };
  330. var getTree = function ( lines ) {
  331. var tree = { 'string': 'Scene', children: [] };
  332. var current = tree;
  333. var matches;
  334. var specification;
  335. for ( var i = 0; i < lines.length; i ++ ) {
  336. var comment = '';
  337. var line = lines[ i ];
  338. // omit whitespace only lines
  339. if ( null !== ( result = /^\s+?$/g.exec( line ) ) ) {
  340. continue;
  341. }
  342. line = line.trim();
  343. // skip empty lines
  344. if ( line === '' ) {
  345. continue;
  346. }
  347. if ( /#/.exec( line ) ) {
  348. var parts = line.split( '#' );
  349. // discard everything after the #, it is a comment
  350. line = parts[ 0 ];
  351. // well, let's also keep the comment
  352. comment = parts[ 1 ];
  353. }
  354. if ( matches = /([^\s]*){1}(?:\s+)?{/.exec( line ) ) {
  355. // first subpattern should match the Node name
  356. var block = { 'nodeType' : matches[ 1 ], 'string': line, 'parent': current, 'children': [], 'comment' : comment };
  357. current.children.push( block );
  358. current = block;
  359. if ( /}/.exec( line ) ) {
  360. // example: geometry Box { size 1 1 1 } # all on the same line
  361. specification = /{(.*)}/.exec( line )[ 1 ];
  362. // todo: remove once new parsing is complete?
  363. block.children.push( specification );
  364. parseProperty( current, specification );
  365. current = current.parent;
  366. }
  367. } else if ( /}/.exec( line ) ) {
  368. current = current.parent;
  369. } else if ( line !== '' ) {
  370. parseProperty( current, line );
  371. // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way
  372. current.children.push( line );
  373. }
  374. }
  375. return tree;
  376. };
  377. var parseNode = function ( data, parent ) {
  378. // console.log( data );
  379. if ( typeof data === 'string' ) {
  380. if ( /USE/.exec( data ) ) {
  381. var defineKey = /USE\s+?([^\s]+)/.exec( data )[ 1 ];
  382. if ( undefined == defines[ defineKey ] ) {
  383. console.warn( defineKey + ' is not defined.' );
  384. } else {
  385. if ( /appearance/.exec( data ) && defineKey ) {
  386. parent.material = defines[ defineKey ].clone();
  387. } else if ( /geometry/.exec( data ) && defineKey ) {
  388. parent.geometry = defines[ defineKey ].clone();
  389. // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it
  390. if ( undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false ) {
  391. parent.geometry.solid = false;
  392. parent.material.side = THREE.DoubleSide;
  393. }
  394. } else if ( defineKey ) {
  395. var object = defines[ defineKey ].clone();
  396. parent.add( object );
  397. }
  398. }
  399. }
  400. return;
  401. }
  402. var object = parent;
  403. if(data.string.indexOf("AmbientLight")>-1 && data.nodeType=='PointLight'){
  404. //wenn im Namen "AmbientLight" vorkommt und es ein PointLight ist,
  405. //diesen Typ in 'AmbientLight' ändern
  406. data.nodeType='AmbientLight';
  407. }
  408. var l_visible = data.on !== undefined ? data.on : true;
  409. var l_intensity = data.intensity !== undefined ? data.intensity : 1;
  410. var l_color = new THREE.Color();
  411. if ( data.color ) l_color.copy( data.color );
  412. if('AmbientLight' === data.nodeType){
  413. object=new THREE.AmbientLight(
  414. l_color.getHex(),
  415. l_intensity
  416. );
  417. object.visible=l_visible;
  418. parent.add( object );
  419. }
  420. else
  421. if('PointLight' === data.nodeType){
  422. var l_distance =0; //0="unendlich" ...1000
  423. if(data.radius!=undefined && data.radius<1000){
  424. //l_radius=data.radius;
  425. l_distance=data.radius;
  426. }
  427. object=new THREE.PointLight(
  428. l_color.getHex(),
  429. l_intensity,
  430. l_distance);
  431. object.visible=l_visible;
  432. parent.add( object );
  433. }
  434. else
  435. if('SpotLight' === data.nodeType){
  436. var l_intensity=1;
  437. var l_distance =0;//0="unendlich"=1000
  438. var l_angle=Math.PI/3;
  439. var l_penumbra=0.0;//0..1
  440. var l_visible=true;
  441. if(data.radius!=undefined && data.radius<1000){
  442. //l_radius=data.radius;
  443. l_distance=data.radius;
  444. }
  445. if(data.cutOffAngle!=undefined)l_angle=data.cutOffAngle;
  446. object = new THREE.SpotLight(
  447. l_color.getHex(),
  448. l_intensity,
  449. l_distance,
  450. l_angle,
  451. l_penumbra
  452. );
  453. object.visible=l_visible;
  454. parent.add( object );
  455. /*
  456. var lightHelper = new THREE.SpotLightHelper( object );
  457. parent.parent.add( lightHelper );
  458. lightHelper.update();
  459. */
  460. }
  461. else
  462. if ( 'Transform' === data.nodeType || 'Group' === data.nodeType ) {
  463. object = new THREE.Object3D();
  464. if ( /DEF/.exec( data.string ) ) {
  465. object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
  466. defines[ object.name ] = object;
  467. }
  468. if ( undefined !== data[ 'translation' ] ) {
  469. var t = data.translation;
  470. object.position.set( t.x, t.y, t.z );
  471. }
  472. if ( undefined !== data.rotation ) {
  473. var r = data.rotation;
  474. object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w );
  475. }
  476. if ( undefined !== data.scale ) {
  477. var s = data.scale;
  478. object.scale.set( s.x, s.y, s.z );
  479. }
  480. parent.add( object );
  481. } else if ( 'Shape' === data.nodeType ) {
  482. object = new THREE.Mesh();
  483. if ( /DEF/.exec( data.string ) ) {
  484. object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
  485. defines[ object.name ] = object;
  486. }
  487. parent.add( object );
  488. } else if ( 'Background' === data.nodeType ) {
  489. var segments = 20;
  490. // sky (full sphere):
  491. var radius = 2e4;
  492. var skyGeometry = new THREE.SphereGeometry( radius, segments, segments );
  493. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide } );
  494. if ( data.skyColor.length > 1 ) {
  495. paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true );
  496. skyMaterial.vertexColors = THREE.VertexColors
  497. } else {
  498. var color = data.skyColor[ 0 ];
  499. skyMaterial.color.setRGB( color.r, color.b, color.g );
  500. }
  501. scene.add( new THREE.Mesh( skyGeometry, skyMaterial ) );
  502. // ground (half sphere):
  503. if ( data.groundColor !== undefined ) {
  504. radius = 1.2e4;
  505. var groundGeometry = new THREE.SphereGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  506. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: THREE.VertexColors } );
  507. paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false );
  508. scene.add( new THREE.Mesh( groundGeometry, groundMaterial ) );
  509. }
  510. } else if ( /geometry/.exec( data.string ) ) {
  511. if ( 'Box' === data.nodeType ) {
  512. var s = data.size;
  513. parent.geometry = new THREE.BoxGeometry( s.x, s.y, s.z );
  514. } else if ( 'Cylinder' === data.nodeType ) {
  515. parent.geometry = new THREE.CylinderGeometry( data.radius, data.radius, data.height );
  516. } else if ( 'Cone' === data.nodeType ) {
  517. parent.geometry = new THREE.CylinderGeometry( data.topRadius, data.bottomRadius, data.height );
  518. } else if ( 'Sphere' === data.nodeType ) {
  519. parent.geometry = new THREE.SphereGeometry( data.radius );
  520. } else if ( 'IndexedFaceSet' === data.nodeType ) {
  521. var geometry = new THREE.Geometry();
  522. var indexes, uvIndexes, uvs;
  523. for ( var i = 0, j = data.children.length; i < j; i ++ ) {
  524. var child = data.children[ i ];
  525. var vec;
  526. if ( 'TextureCoordinate' === child.nodeType ) {
  527. uvs = child.points;
  528. }
  529. if ( 'Coordinate' === child.nodeType ) {
  530. if ( child.points ) {
  531. for ( var k = 0, l = child.points.length; k < l; k ++ ) {
  532. var point = child.points[ k ];
  533. vec = new THREE.Vector3( point.x, point.y, point.z );
  534. geometry.vertices.push( vec );
  535. }
  536. }
  537. if ( child.string.indexOf ( 'DEF' ) > -1 ) {
  538. var name = /DEF\s+([^\s]+)/.exec( child.string )[ 1 ];
  539. defines[ name ] = geometry.vertices;
  540. }
  541. if ( child.string.indexOf ( 'USE' ) > -1 ) {
  542. var defineKey = /USE\s+([^\s]+)/.exec( child.string )[ 1 ];
  543. geometry.vertices = defines[ defineKey ];
  544. }
  545. }
  546. }
  547. var skip = 0;
  548. // some shapes only have vertices for use in other shapes
  549. if ( data.coordIndex ) {
  550. // read this: http://math.hws.edu/eck/cs424/notes2013/16_Threejs_Advanced.html
  551. for ( var i = 0, j = data.coordIndex.length; i < j; i ++ ) {
  552. indexes = data.coordIndex[ i ]; if ( data.texCoordIndex ) uvIndexes = data.texCoordIndex[ i ];
  553. // vrml support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here
  554. skip = 0;
  555. // Face3 only works with triangles, but IndexedFaceSet allows shapes with more then three vertices, build them of triangles
  556. while ( indexes.length >= 3 && skip < ( indexes.length - 2 ) ) {
  557. var face = new THREE.Face3(
  558. indexes[ 0 ],
  559. indexes[ skip + (data.ccw ? 1 : 2) ],
  560. indexes[ skip + (data.ccw ? 2 : 1) ],
  561. null // normal, will be added later
  562. // todo: pass in the color, if a color index is present
  563. );
  564. if ( uvs && uvIndexes ) {
  565. geometry.faceVertexUvs [0].push( [
  566. new THREE.Vector2 (
  567. uvs[ uvIndexes[ 0 ] ].x ,
  568. uvs[ uvIndexes[ 0 ] ].y
  569. ) ,
  570. new THREE.Vector2 (
  571. uvs[ uvIndexes[ skip + (data.ccw ? 1 : 2) ] ].x ,
  572. uvs[ uvIndexes[ skip + (data.ccw ? 1 : 2) ] ].y
  573. ) ,
  574. new THREE.Vector2 (
  575. uvs[ uvIndexes[ skip + (data.ccw ? 2 : 1) ] ].x ,
  576. uvs[ uvIndexes[ skip + (data.ccw ? 2 : 1) ] ].y
  577. )
  578. ] );
  579. }
  580. skip ++;
  581. geometry.faces.push( face );
  582. }
  583. }
  584. } else {
  585. // do not add dummy mesh to the scene
  586. parent.parent.remove( parent );
  587. }
  588. if ( false === data.solid ) {
  589. parent.material.side = THREE.DoubleSide;
  590. }
  591. // we need to store it on the geometry for use with defines
  592. geometry.solid = data.solid;
  593. geometry.computeFaceNormals();
  594. //geometry.computeVertexNormals(); // does not show
  595. geometry.computeBoundingSphere();
  596. // see if it's a define
  597. if ( /DEF/.exec( data.string ) ) {
  598. geometry.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
  599. defines[ geometry.name ] = geometry;
  600. }
  601. parent.geometry = geometry;
  602. }
  603. return;
  604. } else if ( /appearance/.exec( data.string ) ) {
  605. for ( var i = 0; i < data.children.length; i ++ ) {
  606. var child = data.children[ i ];
  607. if ( 'Material' === child.nodeType ) {
  608. var material = new THREE.MeshPhongMaterial();
  609. if ( undefined !== child.diffuseColor ) {
  610. var d = child.diffuseColor;
  611. material.color.setRGB( d.r, d.g, d.b );
  612. }
  613. if ( undefined !== child.emissiveColor ) {
  614. var e = child.emissiveColor;
  615. material.emissive.setRGB( e.r, e.g, e.b );
  616. }
  617. if ( undefined !== child.specularColor ) {
  618. var s = child.specularColor;
  619. material.specular.setRGB( s.r, s.g, s.b );
  620. }
  621. if ( undefined !== child.transparency ) {
  622. var t = child.transparency;
  623. // transparency is opposite of opacity
  624. material.opacity = Math.abs( 1 - t );
  625. material.transparent = true;
  626. }
  627. if ( /DEF/.exec( data.string ) ) {
  628. material.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
  629. defines[ material.name ] = material;
  630. }
  631. parent.material = material;
  632. }
  633. if ( 'ImageTexture' === child.nodeType ) {
  634. var textureName = /"([^"]+)"/.exec(child.children[ 0 ]);
  635. if (textureName) {
  636. parent.material.name = textureName[ 1 ];
  637. parent.material.map = textureLoader.load( texturePath + textureName[ 1 ] );
  638. }
  639. }
  640. }
  641. return;
  642. }
  643. for ( var i = 0, l = data.children.length; i < l; i ++ ) {
  644. parseNode( data.children[ i ], object );
  645. }
  646. };
  647. parseNode( getTree( lines ), scene );
  648. };
  649. var scene = new THREE.Scene();
  650. var lines = data.split( '\n' );
  651. // some lines do not have breaks
  652. for (var i = lines.length -1; i > -1; i--) {
  653. // split lines with {..{ or {..[ - some have both
  654. if (/{.*[{\[]/.test (lines[i])) {
  655. var parts = lines[i].split ('{').join ('{\n').split ('\n');
  656. parts.unshift(1);
  657. parts.unshift(i);
  658. lines.splice.apply(lines, parts);
  659. } else
  660. // split lines with ]..}
  661. if (/\].*}/.test (lines[i])) {
  662. var parts = lines[i].split (']').join (']\n').split ('\n');
  663. parts.unshift(1);
  664. parts.unshift(i);
  665. lines.splice.apply(lines, parts);
  666. }
  667. // split lines with }..}
  668. if (/}.*}/.test (lines[i])) {
  669. var parts = lines[i].split ('}').join ('}\n').split ('\n');
  670. parts.unshift(1);
  671. parts.unshift(i);
  672. lines.splice.apply(lines, parts);
  673. }
  674. // force the parser to create Coordinate node for empty coords
  675. // coord USE something -> coord USE something Coordinate {}
  676. if((lines[i].indexOf ('coord') > -1) && (lines[i].indexOf ('[') < 0) && (lines[i].indexOf ('{') < 0)) {
  677. lines[i] += ' Coordinate {}';
  678. }
  679. }
  680. var header = lines.shift();
  681. if ( /V1.0/.exec( header ) ) {
  682. parseV1( lines, scene );
  683. } else if ( /V2.0/.exec( header ) ) {
  684. parseV2( lines, scene );
  685. }
  686. return scene;
  687. }
  688. };