VRMLLoader.js 25 KB

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