VRMLLoader.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.VRMLLoader = function () {};
  5. THREE.VRMLLoader.prototype = {
  6. constructor: THREE.VRMLLoader,
  7. // for IndexedFaceSet support
  8. isRecordingPoints: false,
  9. isRecordingFaces: false,
  10. points: [],
  11. indexes : [],
  12. // for Background support
  13. isRecordingAngles: false,
  14. isRecordingColors: false,
  15. angles: [],
  16. colors: [],
  17. recordingFieldname: null,
  18. load: function ( url, callback ) {
  19. var scope = this;
  20. var request = new XMLHttpRequest();
  21. request.addEventListener( 'load', function ( event ) {
  22. var object = scope.parse( event.target.responseText );
  23. scope.dispatchEvent( { type: 'load', content: object } );
  24. if ( callback ) callback( object );
  25. }, false );
  26. request.addEventListener( 'progress', function ( event ) {
  27. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  28. }, false );
  29. request.addEventListener( 'error', function () {
  30. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  31. }, false );
  32. request.open( 'GET', url, true );
  33. request.send( null );
  34. },
  35. parse: function ( data ) {
  36. var parseV1 = function ( lines, scene ) {
  37. console.warn( 'VRML V1.0 not supported yet' );
  38. };
  39. var parseV2 = function ( lines, scene ) {
  40. var defines = {};
  41. var float_pattern = /(\b|\-|\+)([\d\.e]+)/;
  42. var float3_pattern = /([\d\.\+\-e]+),?\s+([\d\.\+\-e]+),?\s+([\d\.\+\-e]+)/;
  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 f, n, p, vertexIndex, color;
  86. var direction = directionIsDown ? 1 : -1;
  87. var faceIndices = [ 'a', 'b', 'c', 'd' ];
  88. var coord = [ ], aColor, bColor, t = 1, A = {}, B = {}, applyColor = false, colorIndex;
  89. for ( var k = 0; k < angles.length; k++ ) {
  90. var vec = { };
  91. // push the vector at which the color changes
  92. vec.y = direction * ( Math.cos( angles[k] ) * radius);
  93. vec.x = direction * ( Math.sin( angles[k] ) * radius);
  94. coord.push( vec );
  95. }
  96. // painting the colors on the faces
  97. for ( var i = 0; i < geometry.faces.length ; i++ ) {
  98. f = geometry.faces[ i ];
  99. n = ( f instanceof THREE.Face3 ) ? 3 : 4;
  100. for ( var j = 0; j < n; j++ ) {
  101. vertexIndex = f[ faceIndices[ j ] ];
  102. 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. bColor = colors[ index + 1 ];
  120. aColor = colors[ index ];
  121. // below is simple linear interpolation
  122. 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. color = interpolateColors( aColor, bColor, t );
  125. f.vertexColors[ j ] = color;
  126. }
  127. } else if ( undefined === f.vertexColors[ j ] ) {
  128. colorIndex = directionIsDown ? colors.length -1 : 0;
  129. f.vertexColors[ j ] = colors[ colorIndex ];
  130. }
  131. }
  132. }
  133. }
  134. };
  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, index, 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. this.recordingFieldname = fieldName;
  168. this.isRecordingFaces = true;
  169. this.indexes = [];
  170. break;
  171. }
  172. if (this.isRecordingFaces) {
  173. // the parts hold the indexes as strings
  174. if (parts.length > 0) {
  175. index = [];
  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. this.isRecordingFaces = false;
  196. node.coordIndex = this.indexes;
  197. }
  198. } else if (this.isRecordingPoints) {
  199. parts = float3_pattern.exec(line);
  200. // parts may be empty on first and last line
  201. if (null != parts) {
  202. point = {
  203. x: parseFloat(parts[1]),
  204. y: parseFloat(parts[2]),
  205. z: parseFloat(parts[3])
  206. };
  207. this.points.push(point);
  208. }
  209. // end
  210. if ( /]/.exec(line) ) {
  211. this.isRecordingPoints = false;
  212. node.points = this.points;
  213. }
  214. } else if ( this.isRecordingAngles ) {
  215. // the parts hold the angles as strings
  216. if ( parts.length > 0 ) {
  217. for ( var ind = 0;ind < parts.length; ind++ ) {
  218. // the part should be a float
  219. if ( ! float_pattern.test( parts[ind] ) ) {
  220. continue;
  221. }
  222. this.angles.push( parseFloat( parts[ind] ) );
  223. }
  224. }
  225. // end
  226. if ( /]/.exec(line) ) {
  227. this.isRecordingAngles = false;
  228. node[this.recordingFieldname] = this.angles;
  229. }
  230. } else if (this.isRecordingColors) {
  231. // this is the float3 regex with the g modifier added, you could also explode the line by comma first (faster probably)
  232. var float3_repeatable = /([\d\.\+\-e]+),?\s+([\d\.\+\-e]+),?\s+([\d\.\+\-e]+)/g;
  233. while( null !== (parts = float3_repeatable.exec(line) ) ) {
  234. color = {
  235. r: parseFloat(parts[1]),
  236. g: parseFloat(parts[2]),
  237. b: parseFloat(parts[3])
  238. };
  239. this.colors.push(color);
  240. }
  241. // end
  242. if (/]/.exec(line)) {
  243. this.isRecordingColors = false;
  244. node[this.recordingFieldname] = this.colors;
  245. }
  246. } else if ( parts[parts.length -1] !== 'NULL' && fieldName !== 'children') {
  247. switch (fieldName) {
  248. case 'diffuseColor':
  249. case 'emissiveColor':
  250. case 'specularColor':
  251. case 'color':
  252. if (parts.length != 4) {
  253. console.warn('Invalid color format detected for ' + fieldName );
  254. break;
  255. }
  256. property = {
  257. 'r' : parseFloat(parts[1]),
  258. 'g' : parseFloat(parts[2]),
  259. 'b' : parseFloat(parts[3])
  260. }
  261. break;
  262. case 'translation':
  263. case 'scale':
  264. case 'size':
  265. if (parts.length != 4) {
  266. console.warn('Invalid vector format detected for ' + fieldName);
  267. break;
  268. }
  269. property = {
  270. 'x' : parseFloat(parts[1]),
  271. 'y' : parseFloat(parts[2]),
  272. 'z' : parseFloat(parts[3])
  273. }
  274. break;
  275. case 'radius':
  276. case 'topRadius':
  277. case 'bottomRadius':
  278. case 'height':
  279. case 'transparency':
  280. case 'shininess':
  281. case 'ambientIntensity':
  282. if (parts.length != 2) {
  283. console.warn('Invalid single float value specification detected for ' + fieldName);
  284. break;
  285. }
  286. property = parseFloat(parts[1]);
  287. break;
  288. case 'rotation':
  289. if (parts.length != 5) {
  290. console.warn('Invalid quaternion format detected for ' + fieldName);
  291. break;
  292. }
  293. property = {
  294. 'x' : parseFloat(parts[1]),
  295. 'y' : parseFloat(parts[2]),
  296. 'z' : parseFloat(parts[3]),
  297. 'w' : parseFloat(parts[4])
  298. }
  299. break;
  300. case 'ccw':
  301. case 'solid':
  302. case 'colorPerVertex':
  303. case 'convex':
  304. if (parts.length != 2) {
  305. console.warn('Invalid format detected for ' + fieldName);
  306. break;
  307. }
  308. property = parts[1] === 'TRUE' ? true : false;
  309. break;
  310. }
  311. node[fieldName] = property;
  312. }
  313. return property;
  314. };
  315. var getTree = function ( lines ) {
  316. var tree = { 'string': 'Scene', children: [] };
  317. var current = tree;
  318. var matches;
  319. var specification;
  320. for ( var i = 0; i < lines.length; i ++ ) {
  321. var comment = '';
  322. var line = lines[ i ];
  323. // omit whitespace only lines
  324. if ( null !== ( result = /^\s+?$/g.exec( line ) ) ) {
  325. continue;
  326. }
  327. line = line.trim();
  328. // skip empty lines
  329. if (line === '') {
  330. continue;
  331. }
  332. if ( /#/.exec( line ) ) {
  333. var parts = line.split('#');
  334. // discard everything after the #, it is a comment
  335. line = parts[0];
  336. // well, let's also keep the comment
  337. comment = parts[1];
  338. }
  339. if ( matches = /([^\s]*){1}\s?{/.exec( line ) ) { // first subpattern should match the Node name
  340. var block = { 'nodeType' : matches[1], 'string': line, 'parent': current, 'children': [],'comment' : comment};
  341. current.children.push( block );
  342. current = block;
  343. if ( /}/.exec( line ) ) {
  344. // example: geometry Box { size 1 1 1 } # all on the same line
  345. specification = /{(.*)}/.exec( line )[ 1 ];
  346. // todo: remove once new parsing is complete?
  347. block.children.push( specification );
  348. parseProperty(current, specification);
  349. current = current.parent;
  350. }
  351. } else if ( /}/.exec( line ) ) {
  352. current = current.parent;
  353. } else if ( line !== '' ) {
  354. parseProperty(current, line);
  355. // todo: remove once new parsing is complete? we still do not parse geometry and appearance the new way
  356. current.children.push( line );
  357. }
  358. }
  359. return tree;
  360. }
  361. var parseNode = function ( data, parent ) {
  362. // console.log( data );
  363. if ( typeof data === 'string' ) {
  364. if ( /USE/.exec( data ) ) {
  365. var defineKey = /USE\s+?(\w+)/.exec( data )[ 1 ];
  366. if (undefined == defines[defineKey]) {
  367. console.warn(defineKey + ' is not defined.');
  368. } else {
  369. if ( /appearance/.exec( data ) && defineKey ) {
  370. parent.material = defines[ defineKey ].clone();
  371. } else if ( /geometry/.exec( data ) && defineKey ) {
  372. parent.geometry = defines[ defineKey ].clone();
  373. // the solid property is not cloned with clone(), is only needed for VRML loading, so we need to transfer it
  374. if (undefined !== defines[ defineKey ].solid && defines[ defineKey ].solid === false) {
  375. parent.geometry.solid = false;
  376. parent.material.side = THREE.DoubleSide;
  377. }
  378. } else if (defineKey){
  379. var object = defines[ defineKey ].clone();
  380. parent.add( object );
  381. }
  382. }
  383. }
  384. return;
  385. }
  386. var object = parent;
  387. if ( 'Transform' === data.nodeType || 'Group' === data.nodeType ) {
  388. object = new THREE.Object3D();
  389. if ( /DEF/.exec( data.string ) ) {
  390. object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ];
  391. defines[ object.name ] = object;
  392. }
  393. if ( undefined !== data['translation'] ) {
  394. var t = data.translation;
  395. object.position.set(t.x, t.y, t.z);
  396. }
  397. if ( undefined !== data.rotation ) {
  398. var r = data.rotation;
  399. object.quaternion.setFromAxisAngle( new THREE.Vector3( r.x, r.y, r.z ), r.w );
  400. }
  401. if ( undefined !== data.scale ) {
  402. var s = data.scale;
  403. object.scale.set( s.x, s.y, s.z );
  404. }
  405. parent.add( object );
  406. } else if ( 'Shape' === data.nodeType ) {
  407. object = new THREE.Mesh();
  408. if ( /DEF/.exec( data.string ) ) {
  409. object.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  410. defines[ object.name ] = object;
  411. }
  412. parent.add( object );
  413. } else if ( 'Background' === data.nodeType ) {
  414. var segments = 20;
  415. // sky (full sphere):
  416. var radius = 2e4;
  417. var skyGeometry = new THREE.SphereGeometry( radius, segments, segments );
  418. var skyMaterial = new THREE.MeshBasicMaterial( { color: 'white', vertexColors: THREE.VertexColors, shading: THREE.NoShading } );
  419. skyMaterial.side = THREE.BackSide;
  420. skyMaterial.fog = false;
  421. skyMaterial.color = new THREE.Color();
  422. paintFaces( skyGeometry, radius, data.skyAngle, data.skyColor, true );
  423. var sky = new THREE.Mesh( skyGeometry, skyMaterial );
  424. scene.add( sky );
  425. // ground (half sphere):
  426. radius = 1.2e4;
  427. var groundGeometry = new THREE.SphereGeometry( radius, segments, segments, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  428. var groundMaterial = new THREE.MeshBasicMaterial( { color: 'white', vertexColors: THREE.VertexColors, shading: THREE.NoShading } );
  429. groundMaterial.side = THREE.BackSide;
  430. groundMaterial.fog = false;
  431. groundMaterial.color = new THREE.Color();
  432. paintFaces( groundGeometry, radius, data.groundAngle, data.groundColor, false );
  433. var ground = new THREE.Mesh( groundGeometry, groundMaterial );
  434. scene.add( ground );
  435. } else if ( /geometry/.exec( data.string ) ) {
  436. if ( 'Box' === data.nodeType ) {
  437. var s = data.size;
  438. parent.geometry = new THREE.BoxGeometry( s.x, s.y, s.z );
  439. } else if ( 'Cylinder' === data.nodeType ) {
  440. parent.geometry = new THREE.CylinderGeometry( data.radius, data.radius, data.height );
  441. } else if ( 'Cone' === data.nodeType ) {
  442. parent.geometry = new THREE.CylinderGeometry( data.topRadius, data.bottomRadius, data.height );
  443. } else if ( 'Sphere' === data.nodeType ) {
  444. parent.geometry = new THREE.SphereGeometry( data.radius );
  445. } else if ( 'IndexedFaceSet' === data.nodeType ) {
  446. var geometry = new THREE.Geometry();
  447. var indexes;
  448. for ( var i = 0, j = data.children.length; i < j; i++ ) {
  449. var child = data.children[ i ];
  450. var vec;
  451. if ( 'Coordinate' === child.nodeType ) {
  452. for ( var k = 0, l = child.points.length; k < l; k++ ) {
  453. var point = child.points[ k ];
  454. vec = new THREE.Vector3( point.x, point.y, point.z );
  455. geometry.vertices.push( vec );
  456. }
  457. break;
  458. }
  459. }
  460. var skip = 0;
  461. // read this: http://math.hws.edu/eck/cs424/notes2013/16_Threejs_Advanced.html
  462. for ( var i = 0, j = data.coordIndex.length; i < j; i++ ) {
  463. indexes = data.coordIndex[i];
  464. // vrml support multipoint indexed face sets (more then 3 vertices). You must calculate the composing triangles here
  465. skip = 0;
  466. // todo: this is the time to check if the faces are ordered ccw or not (cw)
  467. // Face3 only works with triangles, but IndexedFaceSet allows shapes with more then three vertices, build them of triangles
  468. while ( indexes.length >= 3 && skip < ( indexes.length -2 ) ) {
  469. var face = new THREE.Face3(
  470. indexes[0],
  471. indexes[skip + 1],
  472. indexes[skip + 2],
  473. null // normal, will be added later
  474. // todo: pass in the color, if a color index is present
  475. );
  476. skip++;
  477. geometry.faces.push( face );
  478. }
  479. }
  480. if ( false === data.solid ) {
  481. parent.material.side = THREE.DoubleSide;
  482. }
  483. // we need to store it on the geometry for use with defines
  484. geometry.solid = data.solid;
  485. geometry.computeFaceNormals();
  486. //geometry.computeVertexNormals(); // does not show
  487. geometry.computeBoundingSphere();
  488. // see if it's a define
  489. if ( /DEF/.exec( data.string ) ) {
  490. geometry.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  491. defines[ geometry.name ] = geometry;
  492. }
  493. parent.geometry = geometry;
  494. }
  495. return;
  496. } else if ( /appearance/.exec( data.string ) ) {
  497. for ( var i = 0; i < data.children.length; i ++ ) {
  498. var child = data.children[ i ];
  499. if ( 'Material' === child.nodeType ) {
  500. var material = new THREE.MeshPhongMaterial();
  501. if ( undefined !== child.diffuseColor ) {
  502. var d = child.diffuseColor;
  503. material.color.setRGB( d.r, d.g, d.b );
  504. }
  505. if ( undefined !== child.emissiveColor ) {
  506. var e = child.emissiveColor;
  507. material.emissive.setRGB( e.r, e.g, e.b );
  508. }
  509. if ( undefined !== child.specularColor ) {
  510. var s = child.specularColor;
  511. material.specular.setRGB( s.r, s.g, s.b );
  512. }
  513. if ( undefined !== child.transparency ) {
  514. var t = child.transparency;
  515. // transparency is opposite of opacity
  516. material.opacity = Math.abs( 1 - t );
  517. material.transparent = true;
  518. }
  519. if ( /DEF/.exec( data.string ) ) {
  520. material.name = /DEF (\w+)/.exec( data.string )[ 1 ];
  521. defines[ material.name ] = material;
  522. }
  523. parent.material = material;
  524. // material found, stop looping
  525. break;
  526. }
  527. }
  528. return;
  529. }
  530. for ( var i = 0, l = data.children.length; i < l; i ++ ) {
  531. var child = data.children[ i ];
  532. parseNode( data.children[ i ], object );
  533. }
  534. }
  535. parseNode( getTree( lines ), scene );
  536. };
  537. var scene = new THREE.Scene();
  538. var lines = data.split( '\n' );
  539. var header = lines.shift();
  540. if ( /V1.0/.exec( header ) ) {
  541. parseV1( lines, scene );
  542. } else if ( /V2.0/.exec( header ) ) {
  543. parseV2( lines, scene );
  544. }
  545. return scene;
  546. }
  547. };
  548. THREE.EventDispatcher.prototype.apply( THREE.VRMLLoader.prototype );