VRMLLoader.js 27 KB

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