VRMLLoader.js 26 KB

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