2
0

VRMLLoader.js 24 KB

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