VRMLLoader.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185
  1. /**
  2. * @author Mugen87 / https://github.com/Mugen87
  3. */
  4. /* global chevrotain */
  5. THREE.VRMLLoader = ( function () {
  6. // dependency check
  7. if ( typeof chevrotain === 'undefined' ) {
  8. throw Error( 'THREE.VRMLLoader: External library chevrotain.min.js required.' );
  9. }
  10. // class definitions
  11. function VRMLLoader( manager ) {
  12. THREE.Loader.call( this, manager );
  13. }
  14. VRMLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  15. constructor: VRMLLoader,
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var path = ( scope.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  19. var loader = new THREE.FileLoader( this.manager );
  20. loader.setPath( scope.path );
  21. loader.load( url, function ( text ) {
  22. onLoad( scope.parse( text, path ) );
  23. }, onProgress, onError );
  24. },
  25. parse: function ( data, path ) {
  26. var nodeMap = {};
  27. function generateVRMLTree( data ) {
  28. // create lexer, parser and visitor
  29. var tokenData = createTokens();
  30. var lexer = new VRMLLexer( tokenData.tokens );
  31. var parser = new VRMLParser( tokenData.tokenVocabulary );
  32. var visitor = createVisitor( parser.getBaseCstVisitorConstructor() );
  33. // lexing
  34. var lexingResult = lexer.lex( data );
  35. parser.input = lexingResult.tokens;
  36. // parsing
  37. var cstOutput = parser.vrml();
  38. if ( parser.errors.length > 0 ) {
  39. console.error( parser.errors );
  40. throw Error( 'THREE.VRMLLoader: Parsing errors detected.' );
  41. }
  42. // actions
  43. var ast = visitor.visit( cstOutput );
  44. return ast;
  45. }
  46. function createTokens() {
  47. var createToken = chevrotain.createToken;
  48. // from http://gun.teipir.gr/VRML-amgem/spec/part1/concepts.html#SyntaxBasics
  49. var RouteIdentifier = createToken( { name: 'RouteIdentifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/ } );
  50. var Identifier = createToken( { name: 'Identifier', pattern: /[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/, longer_alt: RouteIdentifier } );
  51. // from http://gun.teipir.gr/VRML-amgem/spec/part1/nodesRef.html
  52. var nodeTypes = [
  53. 'Anchor', 'Billboard', 'Collision', 'Group', 'Transform', // grouping nodes
  54. 'Inline', 'LOD', 'Switch', // special groups
  55. 'AudioClip', 'DirectionalLight', 'PointLight', 'Script', 'Shape', 'Sound', 'SpotLight', 'WorldInfo', // common nodes
  56. 'CylinderSensor', 'PlaneSensor', 'ProximitySensor', 'SphereSensor', 'TimeSensor', 'TouchSensor', 'VisibilitySensor', // sensors
  57. 'Box', 'Cone', 'Cylinder', 'ElevationGrid', 'Extrusion', 'IndexedFaceSet', 'IndexedLineSet', 'PointSet', 'Sphere', // geometries
  58. 'Color', 'Coordinate', 'Normal', 'TextureCoordinate', // geometric properties
  59. 'Appearance', 'FontStyle', 'ImageTexture', 'Material', 'MovieTexture', 'PixelTexture', 'TextureTransform', // appearance
  60. 'ColorInterpolator', 'CoordinateInterpolator', 'NormalInterpolator', 'OrientationInterpolator', 'PositionInterpolator', 'ScalarInterpolator', // interpolators
  61. 'Background', 'Fog', 'NavigationInfo', 'Viewpoint', // bindable nodes
  62. 'Text' // Text must be placed at the end of the regex so there are no matches for TextureTransform and TextureCoordinate
  63. ];
  64. //
  65. var Version = createToken( {
  66. name: 'Version',
  67. pattern: /#VRML.*/,
  68. longer_alt: Identifier
  69. } );
  70. var NodeName = createToken( {
  71. name: 'NodeName',
  72. pattern: new RegExp( nodeTypes.join( '|' ) ),
  73. longer_alt: Identifier
  74. } );
  75. var DEF = createToken( {
  76. name: 'DEF',
  77. pattern: /DEF/,
  78. longer_alt: Identifier
  79. } );
  80. var USE = createToken( {
  81. name: 'USE',
  82. pattern: /USE/,
  83. longer_alt: Identifier
  84. } );
  85. var ROUTE = createToken( {
  86. name: 'ROUTE',
  87. pattern: /ROUTE/,
  88. longer_alt: Identifier
  89. } );
  90. var TO = createToken( {
  91. name: 'TO',
  92. pattern: /TO/,
  93. longer_alt: Identifier
  94. } );
  95. //
  96. var StringLiteral = createToken( { name: "StringLiteral", pattern: /"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/ } );
  97. var HexLiteral = createToken( { name: 'HexLiteral', pattern: /0[xX][0-9a-fA-F]+/ } );
  98. var NumberLiteral = createToken( { name: 'NumberLiteral', pattern: /[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/ } );
  99. var TrueLiteral = createToken( { name: 'TrueLiteral', pattern: /TRUE/ } );
  100. var FalseLiteral = createToken( { name: 'FalseLiteral', pattern: /FALSE/ } );
  101. var NullLiteral = createToken( { name: 'NullLiteral', pattern: /NULL/ } );
  102. var LSquare = createToken( { name: 'LSquare', pattern: /\[/ } );
  103. var RSquare = createToken( { name: 'RSquare', pattern: /]/ } );
  104. var LCurly = createToken( { name: 'LCurly', pattern: /{/ } );
  105. var RCurly = createToken( { name: 'RCurly', pattern: /}/ } );
  106. var Comment = createToken( {
  107. name: 'Comment',
  108. pattern: /#.*/,
  109. group: chevrotain.Lexer.SKIPPED
  110. } );
  111. // commas, blanks, tabs, newlines and carriage returns are whitespace characters wherever they appear outside of string fields
  112. var WhiteSpace = createToken( {
  113. name: 'WhiteSpace',
  114. pattern: /[ ,\s]/,
  115. group: chevrotain.Lexer.SKIPPED
  116. } );
  117. var tokens = [
  118. WhiteSpace,
  119. // keywords appear before the Identifier
  120. NodeName,
  121. DEF,
  122. USE,
  123. ROUTE,
  124. TO,
  125. TrueLiteral,
  126. FalseLiteral,
  127. NullLiteral,
  128. // the Identifier must appear after the keywords because all keywords are valid identifiers
  129. Version,
  130. Identifier,
  131. RouteIdentifier,
  132. StringLiteral,
  133. HexLiteral,
  134. NumberLiteral,
  135. LSquare,
  136. RSquare,
  137. LCurly,
  138. RCurly,
  139. Comment
  140. ];
  141. var tokenVocabulary = {};
  142. for ( var i = 0, l = tokens.length; i < l; i ++ ) {
  143. var token = tokens[ i ];
  144. tokenVocabulary[ token.name ] = token;
  145. }
  146. return { tokens: tokens, tokenVocabulary: tokenVocabulary };
  147. }
  148. function createVisitor( BaseVRMLVisitor ) {
  149. // the visitor is created dynmaically based on the given base class
  150. function VRMLToASTVisitor() {
  151. BaseVRMLVisitor.call( this );
  152. this.validateVisitor();
  153. }
  154. VRMLToASTVisitor.prototype = Object.assign( Object.create( BaseVRMLVisitor.prototype ), {
  155. constructor: VRMLToASTVisitor,
  156. vrml: function ( ctx ) {
  157. var data = {
  158. version: this.visit( ctx.version ),
  159. nodes: [],
  160. routes: []
  161. };
  162. for ( var i = 0, l = ctx.node.length; i < l; i ++ ) {
  163. var node = ctx.node[ i ];
  164. data.nodes.push( this.visit( node ) );
  165. }
  166. if ( ctx.route ) {
  167. for ( var i = 0, l = ctx.route.length; i < l; i ++ ) {
  168. var route = ctx.route[ i ];
  169. data.routes.push( this.visit( route ) );
  170. }
  171. }
  172. return data;
  173. },
  174. version: function ( ctx ) {
  175. return ctx.Version[ 0 ].image;
  176. },
  177. node: function ( ctx ) {
  178. var data = {
  179. name: ctx.NodeName[ 0 ].image,
  180. fields: []
  181. };
  182. if ( ctx.field ) {
  183. for ( var i = 0, l = ctx.field.length; i < l; i ++ ) {
  184. var field = ctx.field[ i ];
  185. data.fields.push( this.visit( field ) );
  186. }
  187. }
  188. // DEF
  189. if ( ctx.def ) {
  190. data.DEF = this.visit( ctx.def[ 0 ] );
  191. }
  192. return data;
  193. },
  194. field: function ( ctx ) {
  195. var data = {
  196. name: ctx.Identifier[ 0 ].image,
  197. type: null,
  198. values: null
  199. };
  200. var result;
  201. // SFValue
  202. if ( ctx.singleFieldValue ) {
  203. result = this.visit( ctx.singleFieldValue[ 0 ] );
  204. }
  205. // MFValue
  206. if ( ctx.multiFieldValue ) {
  207. result = this.visit( ctx.multiFieldValue[ 0 ] );
  208. }
  209. data.type = result.type;
  210. data.values = result.values;
  211. return data;
  212. },
  213. def: function ( ctx ) {
  214. return ( ctx.Identifier || ctx.NodeName )[ 0 ].image;
  215. },
  216. use: function ( ctx ) {
  217. return { USE: ( ctx.Identifier || ctx.NodeName )[ 0 ].image };
  218. },
  219. singleFieldValue: function ( ctx ) {
  220. return processField( this, ctx );
  221. },
  222. multiFieldValue: function ( ctx ) {
  223. return processField( this, ctx );
  224. },
  225. route: function ( ctx ) {
  226. var data = {
  227. FROM: ctx.RouteIdentifier[ 0 ].image,
  228. TO: ctx.RouteIdentifier[ 1 ].image
  229. };
  230. return data;
  231. }
  232. } );
  233. function processField( scope, ctx ) {
  234. var field = {
  235. type: null,
  236. values: []
  237. };
  238. if ( ctx.node ) {
  239. field.type = 'node';
  240. for ( var i = 0, l = ctx.node.length; i < l; i ++ ) {
  241. var node = ctx.node[ i ];
  242. field.values.push( scope.visit( node ) );
  243. }
  244. }
  245. if ( ctx.use ) {
  246. field.type = 'use';
  247. for ( var i = 0, l = ctx.use.length; i < l; i ++ ) {
  248. var use = ctx.use[ i ];
  249. field.values.push( scope.visit( use ) );
  250. }
  251. }
  252. if ( ctx.StringLiteral ) {
  253. field.type = 'string';
  254. for ( var i = 0, l = ctx.StringLiteral.length; i < l; i ++ ) {
  255. var stringLiteral = ctx.StringLiteral[ i ];
  256. field.values.push( stringLiteral.image.replace( /'|"/g, '' ) );
  257. }
  258. }
  259. if ( ctx.NumberLiteral ) {
  260. field.type = 'number';
  261. for ( var i = 0, l = ctx.NumberLiteral.length; i < l; i ++ ) {
  262. var numberLiteral = ctx.NumberLiteral[ i ];
  263. field.values.push( parseFloat( numberLiteral.image ) );
  264. }
  265. }
  266. if ( ctx.HexLiteral ) {
  267. field.type = 'hex';
  268. for ( var i = 0, l = ctx.HexLiteral.length; i < l; i ++ ) {
  269. var hexLiteral = ctx.HexLiteral[ i ];
  270. field.values.push( hexLiteral.image );
  271. }
  272. }
  273. if ( ctx.TrueLiteral ) {
  274. field.type = 'boolean';
  275. for ( var i = 0, l = ctx.TrueLiteral.length; i < l; i ++ ) {
  276. var trueLiteral = ctx.TrueLiteral[ i ];
  277. if ( trueLiteral.image === 'TRUE' ) field.values.push( true );
  278. }
  279. }
  280. if ( ctx.FalseLiteral ) {
  281. field.type = 'boolean';
  282. for ( var i = 0, l = ctx.FalseLiteral.length; i < l; i ++ ) {
  283. var falseLiteral = ctx.FalseLiteral[ i ];
  284. if ( falseLiteral.image === 'FALSE' ) field.values.push( false );
  285. }
  286. }
  287. if ( ctx.NullLiteral ) {
  288. field.type = 'null';
  289. ctx.NullLiteral.forEach( function () {
  290. field.values.push( null );
  291. } );
  292. }
  293. return field;
  294. }
  295. return new VRMLToASTVisitor();
  296. }
  297. function parseTree( tree ) {
  298. // console.log( JSON.stringify( tree, null, 2 ) );
  299. var nodes = tree.nodes;
  300. var scene = new THREE.Scene();
  301. // first iteration: build nodemap based on DEF statements
  302. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  303. var node = nodes[ i ];
  304. buildNodeMap( node );
  305. }
  306. // second iteration: build nodes
  307. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  308. var node = nodes[ i ];
  309. var object = getNode( node );
  310. if ( object instanceof THREE.Object3D ) scene.add( object );
  311. if ( node.name === 'WorldInfo' ) scene.userData.worldInfo = object;
  312. }
  313. return scene;
  314. }
  315. function buildNodeMap( node ) {
  316. if ( node.DEF ) {
  317. nodeMap[ node.DEF ] = node;
  318. }
  319. var fields = node.fields;
  320. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  321. var field = fields[ i ];
  322. if ( field.type === 'node' ) {
  323. var fieldValues = field.values;
  324. for ( var j = 0, jl = fieldValues.length; j < jl; j ++ ) {
  325. buildNodeMap( fieldValues[ j ] );
  326. }
  327. }
  328. }
  329. }
  330. function getNode( node ) {
  331. // handle case where a node refers to a different one
  332. if ( node.USE ) {
  333. return resolveUSE( node.USE );
  334. }
  335. if ( node.build !== undefined ) return node.build;
  336. node.build = buildNode( node );
  337. return node.build;
  338. }
  339. // node builder
  340. function buildNode( node ) {
  341. var nodeName = node.name;
  342. var build;
  343. switch ( nodeName ) {
  344. case 'Group':
  345. case 'Transform':
  346. build = buildGroupingNode( node );
  347. break;
  348. case 'Background':
  349. build = buildBackgroundNode( node );
  350. break;
  351. case 'Shape':
  352. build = buildShapeNode( node );
  353. break;
  354. case 'Appearance':
  355. build = buildAppearanceNode( node );
  356. break;
  357. case 'Material':
  358. build = buildMaterialNode( node );
  359. break;
  360. case 'ImageTexture':
  361. build = buildImageTextureNode( node );
  362. break;
  363. case 'PixelTexture':
  364. build = buildPixelTextureNode( node );
  365. break;
  366. case 'TextureTransform':
  367. build = buildTextureTransformNode( node );
  368. break;
  369. case 'IndexedFaceSet':
  370. build = buildIndexedFaceSetNode( node );
  371. break;
  372. case 'IndexedLineSet':
  373. build = buildIndexedLineSetNode( node );
  374. break;
  375. case 'PointSet':
  376. build = buildPointSetNode( node );
  377. break;
  378. case 'Box':
  379. build = buildBoxNode( node );
  380. break;
  381. case 'Cone':
  382. build = buildConeNode( node );
  383. break;
  384. case 'Cylinder':
  385. build = buildCylinderNode( node );
  386. break;
  387. case 'Sphere':
  388. build = buildSphereNode( node );
  389. break;
  390. case 'ElevationGrid':
  391. build = buildElevationGridNode( node );
  392. break;
  393. case 'Color':
  394. case 'Coordinate':
  395. case 'Normal':
  396. case 'TextureCoordinate':
  397. build = buildGeometricNode( node );
  398. break;
  399. case 'WorldInfo':
  400. build = buildWorldInfoNode( node );
  401. break;
  402. case 'Anchor':
  403. case 'Billboard':
  404. case 'Collision':
  405. case 'Inline':
  406. case 'LOD':
  407. case 'Switch':
  408. case 'AudioClip':
  409. case 'DirectionalLight':
  410. case 'PointLight':
  411. case 'Script':
  412. case 'Sound':
  413. case 'SpotLight':
  414. case 'CylinderSensor':
  415. case 'PlaneSensor':
  416. case 'ProximitySensor':
  417. case 'SphereSensor':
  418. case 'TimeSensor':
  419. case 'TouchSensor':
  420. case 'VisibilitySensor':
  421. case 'Extrusion':
  422. case 'Text':
  423. case 'FontStyle':
  424. case 'MovieTexture':
  425. case 'ColorInterpolator':
  426. case 'CoordinateInterpolator':
  427. case 'NormalInterpolator':
  428. case 'OrientationInterpolator':
  429. case 'PositionInterpolator':
  430. case 'ScalarInterpolator':
  431. case 'Fog':
  432. case 'NavigationInfo':
  433. case 'Viewpoint':
  434. // node not supported yet
  435. break;
  436. default:
  437. console.warn( 'THREE.VRMLLoader: Unknown node:', nodeName );
  438. break;
  439. }
  440. return build;
  441. }
  442. function buildGroupingNode( node ) {
  443. var object = new THREE.Group();
  444. //
  445. var fields = node.fields;
  446. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  447. var field = fields[ i ];
  448. var fieldName = field.name;
  449. var fieldValues = field.values;
  450. switch ( fieldName ) {
  451. case 'center':
  452. // field not supported
  453. break;
  454. case 'children':
  455. parseFieldChildren( fieldValues, object );
  456. break;
  457. case 'rotation':
  458. var axis = new THREE.Vector3( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  459. var angle = fieldValues[ 3 ];
  460. object.quaternion.setFromAxisAngle( axis, angle );
  461. break;
  462. case 'scale':
  463. object.scale.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  464. break;
  465. case 'scaleOrientation':
  466. // field not supported
  467. break;
  468. case 'translation':
  469. object.position.set( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  470. break;
  471. case 'bboxCenter':
  472. // field not supported
  473. break;
  474. case 'bboxSize':
  475. // field not supported
  476. break;
  477. default:
  478. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  479. break;
  480. }
  481. }
  482. return object;
  483. }
  484. function buildBackgroundNode( node ) {
  485. var group = new THREE.Group();
  486. var groundAngle, groundColor;
  487. var skyAngle, skyColor;
  488. var fields = node.fields;
  489. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  490. var field = fields[ i ];
  491. var fieldName = field.name;
  492. var fieldValues = field.values;
  493. switch ( fieldName ) {
  494. case 'groundAngle':
  495. groundAngle = fieldValues;
  496. break;
  497. case 'groundColor':
  498. groundColor = fieldValues;
  499. break;
  500. case 'backUrl':
  501. // field not supported
  502. break;
  503. case 'bottomUrl':
  504. // field not supported
  505. break;
  506. case 'frontUrl':
  507. // field not supported
  508. break;
  509. case 'leftUrl':
  510. // field not supported
  511. break;
  512. case 'rightUrl':
  513. // field not supported
  514. break;
  515. case 'topUrl':
  516. // field not supported
  517. break;
  518. case 'skyAngle':
  519. skyAngle = fieldValues;
  520. break;
  521. case 'skyColor':
  522. skyColor = fieldValues;
  523. break;
  524. default:
  525. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  526. break;
  527. }
  528. }
  529. var radius = 10000;
  530. // sky
  531. if ( skyColor ) {
  532. var skyGeometry = new THREE.SphereBufferGeometry( radius, 32, 16 );
  533. var skyMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, depthWrite: false, depthTest: false } );
  534. if ( skyColor.length > 3 ) {
  535. paintFaces( skyGeometry, radius, skyAngle, toColorArray( skyColor ), true );
  536. skyMaterial.vertexColors = true;
  537. } else {
  538. skyMaterial.color.setRGB( skyColor[ 0 ], skyColor[ 1 ], skyColor[ 2 ] );
  539. }
  540. var sky = new THREE.Mesh( skyGeometry, skyMaterial );
  541. group.add( sky );
  542. }
  543. // ground
  544. if ( groundColor ) {
  545. if ( groundColor.length > 0 ) {
  546. var groundGeometry = new THREE.SphereBufferGeometry( radius, 32, 16, 0, 2 * Math.PI, 0.5 * Math.PI, 1.5 * Math.PI );
  547. var groundMaterial = new THREE.MeshBasicMaterial( { fog: false, side: THREE.BackSide, vertexColors: true, depthWrite: false, depthTest: false } );
  548. paintFaces( groundGeometry, radius, groundAngle, toColorArray( groundColor ), false );
  549. var ground = new THREE.Mesh( groundGeometry, groundMaterial );
  550. group.add( ground );
  551. }
  552. }
  553. // render background group first
  554. group.renderOrder = - Infinity;
  555. return group;
  556. }
  557. function buildShapeNode( node ) {
  558. var fields = node.fields;
  559. // if the appearance field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0)
  560. var material = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  561. var geometry;
  562. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  563. var field = fields[ i ];
  564. var fieldName = field.name;
  565. var fieldValues = field.values;
  566. switch ( fieldName ) {
  567. case 'appearance':
  568. if ( fieldValues[ 0 ] !== null ) {
  569. material = getNode( fieldValues[ 0 ] );
  570. }
  571. break;
  572. case 'geometry':
  573. if ( fieldValues[ 0 ] !== null ) {
  574. geometry = getNode( fieldValues[ 0 ] );
  575. }
  576. break;
  577. default:
  578. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  579. break;
  580. }
  581. }
  582. // build 3D object
  583. var object;
  584. if ( geometry && geometry.attributes.position ) {
  585. var type = geometry._type;
  586. if ( type === 'points' ) { // points
  587. var pointsMaterial = new THREE.PointsMaterial( { color: 0xffffff } );
  588. if ( geometry.attributes.color !== undefined ) {
  589. pointsMaterial.vertexColors = true;
  590. } else {
  591. // if the color field is NULL and there is a material defined for the appearance affecting this PointSet, then use the emissiveColor of the material to draw the points
  592. if ( material.isMeshPhongMaterial ) {
  593. pointsMaterial.color.copy( material.emissive );
  594. }
  595. }
  596. object = new THREE.Points( geometry, pointsMaterial );
  597. } else if ( type === 'line' ) { // lines
  598. var lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff } );
  599. if ( geometry.attributes.color !== undefined ) {
  600. lineMaterial.vertexColors = true;
  601. } else {
  602. // if the color field is NULL and there is a material defined for the appearance affecting this IndexedLineSet, then use the emissiveColor of the material to draw the lines
  603. if ( material.isMeshPhongMaterial ) {
  604. lineMaterial.color.copy( material.emissive );
  605. }
  606. }
  607. object = new THREE.LineSegments( geometry, lineMaterial );
  608. } else { // consider meshes
  609. // check "solid" hint (it's placed in the geometry but affects the material)
  610. if ( geometry._solid !== undefined ) {
  611. material.side = ( geometry._solid ) ? THREE.FrontSide : THREE.DoubleSide;
  612. }
  613. // check for vertex colors
  614. if ( geometry.attributes.color !== undefined ) {
  615. material.vertexColors = true;
  616. }
  617. object = new THREE.Mesh( geometry, material );
  618. }
  619. } else {
  620. object = new THREE.Object3D();
  621. // if the geometry field is NULL or no vertices are defined the object is not drawn
  622. object.visible = false;
  623. }
  624. return object;
  625. }
  626. function buildAppearanceNode( node ) {
  627. var material = new THREE.MeshPhongMaterial();
  628. var transformData;
  629. var fields = node.fields;
  630. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  631. var field = fields[ i ];
  632. var fieldName = field.name;
  633. var fieldValues = field.values;
  634. switch ( fieldName ) {
  635. case 'material':
  636. if ( fieldValues[ 0 ] !== null ) {
  637. var materialData = getNode( fieldValues[ 0 ] );
  638. if ( materialData.diffuseColor ) material.color.copy( materialData.diffuseColor );
  639. if ( materialData.emissiveColor ) material.emissive.copy( materialData.emissiveColor );
  640. if ( materialData.shininess ) material.shininess = materialData.shininess;
  641. if ( materialData.specularColor ) material.specular.copy( materialData.specularColor );
  642. if ( materialData.transparency ) material.opacity = 1 - materialData.transparency;
  643. if ( materialData.transparency > 0 ) material.transparent = true;
  644. } else {
  645. // if the material field is NULL or unspecified, lighting is off and the unlit object color is (0, 0, 0)
  646. material = new THREE.MeshBasicMaterial( { color: 0x000000 } );
  647. }
  648. break;
  649. case 'texture':
  650. var textureNode = fieldValues[ 0 ];
  651. if ( textureNode !== null ) {
  652. if ( textureNode.name === 'ImageTexture' || textureNode.name === 'PixelTexture' ) {
  653. material.map = getNode( textureNode );
  654. } else {
  655. // MovieTexture not supported yet
  656. }
  657. }
  658. break;
  659. case 'textureTransform':
  660. if ( fieldValues[ 0 ] !== null ) {
  661. transformData = getNode( fieldValues[ 0 ] );
  662. }
  663. break;
  664. default:
  665. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  666. break;
  667. }
  668. }
  669. // only apply texture transform data if a texture was defined
  670. if ( material.map ) {
  671. // respect VRML lighting model
  672. if ( material.map.__type ) {
  673. switch ( material.map.__type ) {
  674. case TEXTURE_TYPE.INTENSITY_ALPHA:
  675. material.opacity = 1; // ignore transparency
  676. break;
  677. case TEXTURE_TYPE.RGB:
  678. material.color.set( 0xffffff ); // ignore material color
  679. break;
  680. case TEXTURE_TYPE.RGBA:
  681. material.color.set( 0xffffff ); // ignore material color
  682. material.opacity = 1; // ignore transparency
  683. break;
  684. default:
  685. }
  686. delete material.map.__type;
  687. }
  688. // apply texture transform
  689. if ( transformData ) {
  690. material.map.center.copy( transformData.center );
  691. material.map.rotation = transformData.rotation;
  692. material.map.repeat.copy( transformData.scale );
  693. material.map.offset.copy( transformData.translation );
  694. }
  695. }
  696. return material;
  697. }
  698. function buildMaterialNode( node ) {
  699. var materialData = {};
  700. var fields = node.fields;
  701. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  702. var field = fields[ i ];
  703. var fieldName = field.name;
  704. var fieldValues = field.values;
  705. switch ( fieldName ) {
  706. case 'ambientIntensity':
  707. // field not supported
  708. break;
  709. case 'diffuseColor':
  710. materialData.diffuseColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  711. break;
  712. case 'emissiveColor':
  713. materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  714. break;
  715. case 'shininess':
  716. materialData.shininess = fieldValues[ 0 ];
  717. break;
  718. case 'specularColor':
  719. materialData.emissiveColor = new THREE.Color( fieldValues[ 0 ], fieldValues[ 1 ], fieldValues[ 2 ] );
  720. break;
  721. case 'transparency':
  722. materialData.transparency = fieldValues[ 0 ];
  723. break;
  724. default:
  725. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  726. break;
  727. }
  728. }
  729. return materialData;
  730. }
  731. function parseHexColor( hex, textureType, color ) {
  732. switch ( textureType ) {
  733. case TEXTURE_TYPE.INTENSITY:
  734. // Intensity texture: A one-component image specifies one-byte hexadecimal or integer values representing the intensity of the image
  735. var value = parseInt( hex );
  736. color.r = value;
  737. color.g = value;
  738. color.b = value;
  739. break;
  740. case TEXTURE_TYPE.INTENSITY_ALPHA:
  741. // Intensity+Alpha texture: A two-component image specifies the intensity in the first (high) byte and the alpha opacity in the second (low) byte.
  742. var value = parseInt( "0x" + hex.substring( 2, 4 ) );
  743. color.r = value;
  744. color.g = value;
  745. color.b = value;
  746. color.a = parseInt( "0x" + hex.substring( 4, 6 ) );
  747. break;
  748. case TEXTURE_TYPE.RGB:
  749. // RGB texture: Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components
  750. color.r = parseInt( "0x" + hex.substring( 2, 4 ) );
  751. color.g = parseInt( "0x" + hex.substring( 4, 6 ) );
  752. color.b = parseInt( "0x" + hex.substring( 6, 8 ) );
  753. break;
  754. case TEXTURE_TYPE.RGBA:
  755. // RGBA texture: Four-component images specify the alpha opacity byte after red/green/blue
  756. color.r = parseInt( "0x" + hex.substring( 2, 4 ) );
  757. color.g = parseInt( "0x" + hex.substring( 4, 6 ) );
  758. color.b = parseInt( "0x" + hex.substring( 6, 8 ) );
  759. color.a = parseInt( "0x" + hex.substring( 8, 10 ) );
  760. break;
  761. default:
  762. }
  763. }
  764. function getTextureType( num_components ) {
  765. var type;
  766. switch ( num_components ) {
  767. case 1:
  768. type = TEXTURE_TYPE.INTENSITY;
  769. break;
  770. case 2:
  771. type = TEXTURE_TYPE.INTENSITY_ALPHA;
  772. break;
  773. case 3:
  774. type = TEXTURE_TYPE.RGB;
  775. break;
  776. case 4:
  777. type = TEXTURE_TYPE.RGBA;
  778. break;
  779. default:
  780. }
  781. return type;
  782. }
  783. function buildPixelTextureNode( node ) {
  784. var texture;
  785. var wrapS = THREE.RepeatWrapping;
  786. var wrapT = THREE.RepeatWrapping;
  787. var fields = node.fields;
  788. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  789. var field = fields[ i ];
  790. var fieldName = field.name;
  791. var fieldValues = field.values;
  792. switch ( fieldName ) {
  793. case 'image':
  794. var width = fieldValues[ 0 ];
  795. var height = fieldValues[ 1 ];
  796. var num_components = fieldValues[ 2 ];
  797. var useAlpha = ( num_components === 2 || num_components === 4 );
  798. var textureType = getTextureType( num_components );
  799. var size = ( ( useAlpha === true ) ? 4 : 3 ) * ( width * height );
  800. var data = new Uint8Array( size );
  801. var color = { r: 0, g: 0, b: 0, a: 0 };
  802. for ( var j = 3, k = 0, jl = fieldValues.length; j < jl; j ++, k ++ ) {
  803. parseHexColor( fieldValues[ j ], textureType, color );
  804. if ( useAlpha === true ) {
  805. var stride = k * 4;
  806. data[ stride + 0 ] = color.r;
  807. data[ stride + 1 ] = color.g;
  808. data[ stride + 2 ] = color.b;
  809. data[ stride + 3 ] = color.a;
  810. } else {
  811. var stride = k * 3;
  812. data[ stride + 0 ] = color.r;
  813. data[ stride + 1 ] = color.g;
  814. data[ stride + 2 ] = color.b;
  815. }
  816. }
  817. texture = new THREE.DataTexture( data, width, height, ( useAlpha === true ) ? THREE.RGBAFormat : THREE.RGBFormat );
  818. texture.__type = textureType; // needed for material modifications
  819. break;
  820. case 'repeatS':
  821. if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping;
  822. break;
  823. case 'repeatT':
  824. if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping;
  825. break;
  826. default:
  827. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  828. break;
  829. }
  830. }
  831. if ( texture ) {
  832. texture.wrapS = wrapS;
  833. texture.wrapT = wrapT;
  834. }
  835. return texture;
  836. }
  837. function buildImageTextureNode( node ) {
  838. var texture;
  839. var wrapS = THREE.RepeatWrapping;
  840. var wrapT = THREE.RepeatWrapping;
  841. var fields = node.fields;
  842. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  843. var field = fields[ i ];
  844. var fieldName = field.name;
  845. var fieldValues = field.values;
  846. switch ( fieldName ) {
  847. case 'url':
  848. var url = fieldValues[ 0 ];
  849. if ( url ) texture = textureLoader.load( url );
  850. break;
  851. case 'repeatS':
  852. if ( fieldValues[ 0 ] === false ) wrapS = THREE.ClampToEdgeWrapping;
  853. break;
  854. case 'repeatT':
  855. if ( fieldValues[ 0 ] === false ) wrapT = THREE.ClampToEdgeWrapping;
  856. break;
  857. default:
  858. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  859. break;
  860. }
  861. }
  862. if ( texture ) {
  863. texture.wrapS = wrapS;
  864. texture.wrapT = wrapT;
  865. }
  866. return texture;
  867. }
  868. function buildTextureTransformNode( node ) {
  869. var transformData = {
  870. center: new THREE.Vector2(),
  871. rotation: new THREE.Vector2(),
  872. scale: new THREE.Vector2(),
  873. translation: new THREE.Vector2()
  874. };
  875. var fields = node.fields;
  876. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  877. var field = fields[ i ];
  878. var fieldName = field.name;
  879. var fieldValues = field.values;
  880. switch ( fieldName ) {
  881. case 'center':
  882. transformData.center.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  883. break;
  884. case 'rotation':
  885. transformData.rotation = fieldValues[ 0 ];
  886. break;
  887. case 'scale':
  888. transformData.scale.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  889. break;
  890. case 'translation':
  891. transformData.translation.set( fieldValues[ 0 ], fieldValues[ 1 ] );
  892. break;
  893. default:
  894. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  895. break;
  896. }
  897. }
  898. return transformData;
  899. }
  900. function buildGeometricNode( node ) {
  901. return node.fields[ 0 ].values;
  902. }
  903. function buildWorldInfoNode( node ) {
  904. var worldInfo = {};
  905. var fields = node.fields;
  906. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  907. var field = fields[ i ];
  908. var fieldName = field.name;
  909. var fieldValues = field.values;
  910. switch ( fieldName ) {
  911. case 'title':
  912. worldInfo.title = fieldValues[ 0 ];
  913. break;
  914. case 'info':
  915. worldInfo.info = fieldValues;
  916. break;
  917. default:
  918. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  919. break;
  920. }
  921. }
  922. return worldInfo;
  923. }
  924. function buildIndexedFaceSetNode( node ) {
  925. var color, coord, normal, texCoord;
  926. var ccw = true, solid = true, creaseAngle = 0;
  927. var colorIndex, coordIndex, normalIndex, texCoordIndex;
  928. var colorPerVertex = true, normalPerVertex = true;
  929. var fields = node.fields;
  930. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  931. var field = fields[ i ];
  932. var fieldName = field.name;
  933. var fieldValues = field.values;
  934. switch ( fieldName ) {
  935. case 'color':
  936. var colorNode = fieldValues[ 0 ];
  937. if ( colorNode !== null ) {
  938. color = getNode( colorNode );
  939. }
  940. break;
  941. case 'coord':
  942. var coordNode = fieldValues[ 0 ];
  943. if ( coordNode !== null ) {
  944. coord = getNode( coordNode );
  945. }
  946. break;
  947. case 'normal':
  948. var normalNode = fieldValues[ 0 ];
  949. if ( normalNode !== null ) {
  950. normal = getNode( normalNode );
  951. }
  952. break;
  953. case 'texCoord':
  954. var texCoordNode = fieldValues[ 0 ];
  955. if ( texCoordNode !== null ) {
  956. texCoord = getNode( texCoordNode );
  957. }
  958. break;
  959. case 'ccw':
  960. ccw = fieldValues[ 0 ];
  961. break;
  962. case 'colorIndex':
  963. colorIndex = fieldValues;
  964. break;
  965. case 'colorPerVertex':
  966. colorPerVertex = fieldValues[ 0 ];
  967. break;
  968. case 'convex':
  969. // field not supported
  970. break;
  971. case 'coordIndex':
  972. coordIndex = fieldValues;
  973. break;
  974. case 'creaseAngle':
  975. creaseAngle = fieldValues[ 0 ];
  976. break;
  977. case 'normalIndex':
  978. normalIndex = fieldValues;
  979. break;
  980. case 'normalPerVertex':
  981. normalPerVertex = fieldValues[ 0 ];
  982. break;
  983. case 'solid':
  984. solid = fieldValues[ 0 ];
  985. break;
  986. case 'texCoordIndex':
  987. texCoordIndex = fieldValues;
  988. break;
  989. default:
  990. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  991. break;
  992. }
  993. }
  994. if ( coordIndex === undefined ) {
  995. console.warn( 'THREE.VRMLLoader: Missing coordIndex.' );
  996. return new THREE.BufferGeometry(); // handle VRML files with incomplete geometry definition
  997. }
  998. var triangulatedCoordIndex = triangulateFaceIndex( coordIndex, ccw );
  999. var positionAttribute;
  1000. var colorAttribute;
  1001. var normalAttribute;
  1002. var uvAttribute;
  1003. if ( color ) {
  1004. if ( colorPerVertex === true ) {
  1005. if ( colorIndex && colorIndex.length > 0 ) {
  1006. // if the colorIndex field is not empty, then it is used to choose colors for each vertex of the IndexedFaceSet.
  1007. var triangulatedColorIndex = triangulateFaceIndex( colorIndex, ccw );
  1008. colorAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedColorIndex, color, 3 );
  1009. } else {
  1010. // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node
  1011. colorAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( color, 3 ) );
  1012. }
  1013. } else {
  1014. if ( colorIndex && colorIndex.length > 0 ) {
  1015. // if the colorIndex field is not empty, then they are used to choose one color for each face of the IndexedFaceSet
  1016. var flattenFaceColors = flattenData( color, colorIndex );
  1017. var triangulatedFaceColors = triangulateFaceData( flattenFaceColors, coordIndex );
  1018. colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors );
  1019. } else {
  1020. // if the colorIndex field is empty, then the color are applied to each face of the IndexedFaceSet in order
  1021. var triangulatedFaceColors = triangulateFaceData( color, coordIndex );
  1022. colorAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceColors );
  1023. }
  1024. }
  1025. }
  1026. if ( normal ) {
  1027. if ( normalPerVertex === true ) {
  1028. // consider vertex normals
  1029. if ( normalIndex && normalIndex.length > 0 ) {
  1030. // if the normalIndex field is not empty, then it is used to choose normals for each vertex of the IndexedFaceSet.
  1031. var triangulatedNormalIndex = triangulateFaceIndex( normalIndex, ccw );
  1032. normalAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedNormalIndex, normal, 3 );
  1033. } else {
  1034. // if the normalIndex field is empty, then the coordIndex field is used to choose normals from the Normal node
  1035. normalAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( normal, 3 ) );
  1036. }
  1037. } else {
  1038. // consider face normals
  1039. if ( normalIndex && normalIndex.length > 0 ) {
  1040. // if the normalIndex field is not empty, then they are used to choose one normal for each face of the IndexedFaceSet
  1041. var flattenFaceNormals = flattenData( normal, normalIndex );
  1042. var triangulatedFaceNormals = triangulateFaceData( flattenFaceNormals, coordIndex );
  1043. normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals );
  1044. } else {
  1045. // if the normalIndex field is empty, then the normals are applied to each face of the IndexedFaceSet in order
  1046. var triangulatedFaceNormals = triangulateFaceData( normal, coordIndex );
  1047. normalAttribute = computeAttributeFromFaceData( triangulatedCoordIndex, triangulatedFaceNormals );
  1048. }
  1049. }
  1050. } else {
  1051. // if the normal field is NULL, then the loader should automatically generate normals, using creaseAngle to determine if and how normals are smoothed across shared vertices
  1052. normalAttribute = computeNormalAttribute( triangulatedCoordIndex, coord, creaseAngle );
  1053. }
  1054. if ( texCoord ) {
  1055. // texture coordinates are always defined on vertex level
  1056. if ( texCoordIndex && texCoordIndex.length > 0 ) {
  1057. // if the texCoordIndex field is not empty, then it is used to choose texture coordinates for each vertex of the IndexedFaceSet.
  1058. var triangulatedTexCoordIndex = triangulateFaceIndex( texCoordIndex, ccw );
  1059. uvAttribute = computeAttributeFromIndexedData( triangulatedCoordIndex, triangulatedTexCoordIndex, texCoord, 2 );
  1060. } else {
  1061. // if the texCoordIndex field is empty, then the coordIndex array is used to choose texture coordinates from the TextureCoordinate node
  1062. uvAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( texCoord, 2 ) );
  1063. }
  1064. }
  1065. var geometry = new THREE.BufferGeometry();
  1066. positionAttribute = toNonIndexedAttribute( triangulatedCoordIndex, new THREE.Float32BufferAttribute( coord, 3 ) );
  1067. geometry.setAttribute( 'position', positionAttribute );
  1068. geometry.setAttribute( 'normal', normalAttribute );
  1069. // optional attributes
  1070. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1071. if ( uvAttribute ) geometry.setAttribute( 'uv', uvAttribute );
  1072. // "solid" influences the material so let's store it for later use
  1073. geometry._solid = solid;
  1074. geometry._type = 'mesh';
  1075. return geometry;
  1076. }
  1077. function buildIndexedLineSetNode( node ) {
  1078. var color, coord;
  1079. var colorIndex, coordIndex;
  1080. var colorPerVertex = true;
  1081. var fields = node.fields;
  1082. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1083. var field = fields[ i ];
  1084. var fieldName = field.name;
  1085. var fieldValues = field.values;
  1086. switch ( fieldName ) {
  1087. case 'color':
  1088. var colorNode = fieldValues[ 0 ];
  1089. if ( colorNode !== null ) {
  1090. color = getNode( colorNode );
  1091. }
  1092. break;
  1093. case 'coord':
  1094. var coordNode = fieldValues[ 0 ];
  1095. if ( coordNode !== null ) {
  1096. coord = getNode( coordNode );
  1097. }
  1098. break;
  1099. case 'colorIndex':
  1100. colorIndex = fieldValues;
  1101. break;
  1102. case 'colorPerVertex':
  1103. colorPerVertex = fieldValues[ 0 ];
  1104. break;
  1105. case 'coordIndex':
  1106. coordIndex = fieldValues;
  1107. break;
  1108. default:
  1109. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1110. break;
  1111. }
  1112. }
  1113. // build lines
  1114. var colorAttribute;
  1115. var expandedLineIndex = expandLineIndex( coordIndex ); // create an index for three.js's linesegment primitive
  1116. if ( color ) {
  1117. if ( colorPerVertex === true ) {
  1118. if ( colorIndex.length > 0 ) {
  1119. // if the colorIndex field is not empty, then one color is used for each polyline of the IndexedLineSet.
  1120. var expandedColorIndex = expandLineIndex( colorIndex ); // compute colors for each line segment (rendering primitve)
  1121. colorAttribute = computeAttributeFromIndexedData( expandedLineIndex, expandedColorIndex, color, 3 ); // compute data on vertex level
  1122. } else {
  1123. // if the colorIndex field is empty, then the colors are applied to each polyline of the IndexedLineSet in order.
  1124. colorAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( color, 3 ) );
  1125. }
  1126. } else {
  1127. if ( colorIndex.length > 0 ) {
  1128. // if the colorIndex field is not empty, then colors are applied to each vertex of the IndexedLineSet
  1129. var flattenLineColors = flattenData( color, colorIndex ); // compute colors for each VRML primitve
  1130. var expandedLineColors = expandLineData( flattenLineColors, coordIndex ); // compute colors for each line segment (rendering primitve)
  1131. colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level
  1132. } else {
  1133. // if the colorIndex field is empty, then the coordIndex field is used to choose colors from the Color node
  1134. var expandedLineColors = expandLineData( color, coordIndex ); // compute colors for each line segment (rendering primitve)
  1135. colorAttribute = computeAttributeFromLineData( expandedLineIndex, expandedLineColors ); // compute data on vertex level
  1136. }
  1137. }
  1138. }
  1139. //
  1140. var geometry = new THREE.BufferGeometry();
  1141. var positionAttribute = toNonIndexedAttribute( expandedLineIndex, new THREE.Float32BufferAttribute( coord, 3 ) );
  1142. geometry.setAttribute( 'position', positionAttribute );
  1143. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1144. geometry._type = 'line';
  1145. return geometry;
  1146. }
  1147. function buildPointSetNode( node ) {
  1148. var geometry;
  1149. var color, coord;
  1150. var fields = node.fields;
  1151. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1152. var field = fields[ i ];
  1153. var fieldName = field.name;
  1154. var fieldValues = field.values;
  1155. switch ( fieldName ) {
  1156. case 'color':
  1157. var colorNode = fieldValues[ 0 ];
  1158. if ( colorNode !== null ) {
  1159. color = getNode( colorNode );
  1160. }
  1161. break;
  1162. case 'coord':
  1163. var coordNode = fieldValues[ 0 ];
  1164. if ( coordNode !== null ) {
  1165. coord = getNode( coordNode );
  1166. }
  1167. break;
  1168. default:
  1169. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1170. break;
  1171. }
  1172. }
  1173. var geometry = new THREE.BufferGeometry();
  1174. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( coord, 3 ) );
  1175. if ( color ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color, 3 ) );
  1176. geometry._type = 'points';
  1177. return geometry;
  1178. }
  1179. function buildBoxNode( node ) {
  1180. var size = new THREE.Vector3( 2, 2, 2 );
  1181. var fields = node.fields;
  1182. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1183. var field = fields[ i ];
  1184. var fieldName = field.name;
  1185. var fieldValues = field.values;
  1186. switch ( fieldName ) {
  1187. case 'size':
  1188. size.x = fieldValues[ 0 ];
  1189. size.y = fieldValues[ 1 ];
  1190. size.z = fieldValues[ 2 ];
  1191. break;
  1192. default:
  1193. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1194. break;
  1195. }
  1196. }
  1197. var geometry = new THREE.BoxBufferGeometry( size.x, size.y, size.z );
  1198. return geometry;
  1199. }
  1200. function buildConeNode( node ) {
  1201. var radius = 1, height = 2, openEnded = false;
  1202. var fields = node.fields;
  1203. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1204. var field = fields[ i ];
  1205. var fieldName = field.name;
  1206. var fieldValues = field.values;
  1207. switch ( fieldName ) {
  1208. case 'bottom':
  1209. openEnded = ! fieldValues[ 0 ];
  1210. break;
  1211. case 'bottomRadius':
  1212. radius = fieldValues[ 0 ];
  1213. break;
  1214. case 'height':
  1215. height = fieldValues[ 0 ];
  1216. break;
  1217. case 'side':
  1218. // field not supported
  1219. break;
  1220. default:
  1221. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1222. break;
  1223. }
  1224. }
  1225. var geometry = new THREE.ConeBufferGeometry( radius, height, 16, 1, openEnded );
  1226. return geometry;
  1227. }
  1228. function buildCylinderNode( node ) {
  1229. var radius = 1, height = 2;
  1230. var fields = node.fields;
  1231. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1232. var field = fields[ i ];
  1233. var fieldName = field.name;
  1234. var fieldValues = field.values;
  1235. switch ( fieldName ) {
  1236. case 'bottom':
  1237. // field not supported
  1238. break;
  1239. case 'radius':
  1240. radius = fieldValues[ 0 ];
  1241. break;
  1242. case 'height':
  1243. height = fieldValues[ 0 ];
  1244. break;
  1245. case 'side':
  1246. // field not supported
  1247. break;
  1248. case 'top':
  1249. // field not supported
  1250. break;
  1251. default:
  1252. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1253. break;
  1254. }
  1255. }
  1256. var geometry = new THREE.CylinderBufferGeometry( radius, radius, height, 16, 1 );
  1257. return geometry;
  1258. }
  1259. function buildSphereNode( node ) {
  1260. var radius = 1;
  1261. var fields = node.fields;
  1262. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1263. var field = fields[ i ];
  1264. var fieldName = field.name;
  1265. var fieldValues = field.values;
  1266. switch ( fieldName ) {
  1267. case 'radius':
  1268. radius = fieldValues[ 0 ];
  1269. break;
  1270. default:
  1271. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1272. break;
  1273. }
  1274. }
  1275. var geometry = new THREE.SphereBufferGeometry( radius, 16, 16 );
  1276. return geometry;
  1277. }
  1278. function buildElevationGridNode( node ) {
  1279. var color;
  1280. var normal;
  1281. var texCoord;
  1282. var height;
  1283. var colorPerVertex = true;
  1284. var normalPerVertex = true;
  1285. var solid = true;
  1286. var ccw = true;
  1287. var creaseAngle = 0;
  1288. var xDimension = 2;
  1289. var zDimension = 2;
  1290. var xSpacing = 1;
  1291. var zSpacing = 1;
  1292. var fields = node.fields;
  1293. for ( var i = 0, l = fields.length; i < l; i ++ ) {
  1294. var field = fields[ i ];
  1295. var fieldName = field.name;
  1296. var fieldValues = field.values;
  1297. switch ( fieldName ) {
  1298. case 'color':
  1299. var colorNode = fieldValues[ 0 ];
  1300. if ( colorNode !== null ) {
  1301. color = getNode( colorNode );
  1302. }
  1303. break;
  1304. case 'normal':
  1305. var normalNode = fieldValues[ 0 ];
  1306. if ( normalNode !== null ) {
  1307. normal = getNode( normalNode );
  1308. }
  1309. break;
  1310. case 'texCoord':
  1311. var texCoordNode = fieldValues[ 0 ];
  1312. if ( texCoordNode !== null ) {
  1313. texCoord = getNode( texCoordNode );
  1314. }
  1315. break;
  1316. case 'height':
  1317. height = fieldValues;
  1318. break;
  1319. case 'ccw':
  1320. ccw = fieldValues[ 0 ];
  1321. break;
  1322. case 'colorPerVertex':
  1323. colorPerVertex = fieldValues[ 0 ];
  1324. break;
  1325. case 'creaseAngle':
  1326. creaseAngle = fieldValues[ 0 ];
  1327. break;
  1328. case 'normalPerVertex':
  1329. normalPerVertex = fieldValues[ 0 ];
  1330. break;
  1331. case 'solid':
  1332. solid = fieldValues[ 0 ];
  1333. break;
  1334. case 'xDimension':
  1335. xDimension = fieldValues[ 0 ];
  1336. break;
  1337. case 'xSpacing':
  1338. xSpacing = fieldValues[ 0 ];
  1339. break;
  1340. case 'zDimension':
  1341. zDimension = fieldValues[ 0 ];
  1342. break;
  1343. case 'zSpacing':
  1344. zSpacing = fieldValues[ 0 ];
  1345. break;
  1346. default:
  1347. console.warn( 'THREE.VRMLLoader: Unknown field:', fieldName );
  1348. break;
  1349. }
  1350. }
  1351. // vertex data
  1352. var vertices = [];
  1353. var normals = [];
  1354. var colors = [];
  1355. var uvs = [];
  1356. for ( var i = 0; i < zDimension; i ++ ) {
  1357. for ( var j = 0; j < xDimension; j ++ ) {
  1358. // compute a row major index
  1359. var index = ( i * xDimension ) + j;
  1360. // vertices
  1361. var x = xSpacing * i;
  1362. var y = height[ index ];
  1363. var z = zSpacing * j;
  1364. vertices.push( x, y, z );
  1365. // colors
  1366. if ( color && colorPerVertex === true ) {
  1367. var r = color[ index * 3 + 0 ];
  1368. var g = color[ index * 3 + 1 ];
  1369. var b = color[ index * 3 + 2 ];
  1370. colors.push( r, g, b );
  1371. }
  1372. // normals
  1373. if ( normal && normalPerVertex === true ) {
  1374. var xn = normal[ index * 3 + 0 ];
  1375. var yn = normal[ index * 3 + 1 ];
  1376. var zn = normal[ index * 3 + 2 ];
  1377. normals.push( xn, yn, zn );
  1378. }
  1379. // uvs
  1380. if ( texCoord ) {
  1381. var s = texCoord[ index * 2 + 0 ];
  1382. var t = texCoord[ index * 2 + 1 ];
  1383. uvs.push( s, t );
  1384. } else {
  1385. uvs.push( i / ( xDimension - 1 ), j / ( zDimension - 1 ) );
  1386. }
  1387. }
  1388. }
  1389. // indices
  1390. var indices = [];
  1391. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1392. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1393. // from https://tecfa.unige.ch/guides/vrml/vrml97/spec/part1/nodesRef.html#ElevationGrid
  1394. var a = i + j * xDimension;
  1395. var b = i + ( j + 1 ) * xDimension;
  1396. var c = ( i + 1 ) + ( j + 1 ) * xDimension;
  1397. var d = ( i + 1 ) + j * xDimension;
  1398. // faces
  1399. if ( ccw === true ) {
  1400. indices.push( a, c, b );
  1401. indices.push( c, a, d );
  1402. } else {
  1403. indices.push( a, b, c );
  1404. indices.push( c, d, a );
  1405. }
  1406. }
  1407. }
  1408. //
  1409. var positionAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( vertices, 3 ) );
  1410. var uvAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( uvs, 2 ) );
  1411. var colorAttribute;
  1412. var normalAttribute;
  1413. // color attribute
  1414. if ( color ) {
  1415. if ( colorPerVertex === false ) {
  1416. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1417. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1418. var index = i + j * ( xDimension - 1 );
  1419. var r = color[ index * 3 + 0 ];
  1420. var g = color[ index * 3 + 1 ];
  1421. var b = color[ index * 3 + 2 ];
  1422. // one color per quad
  1423. colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b );
  1424. colors.push( r, g, b ); colors.push( r, g, b ); colors.push( r, g, b );
  1425. }
  1426. }
  1427. colorAttribute = new THREE.Float32BufferAttribute( colors, 3 );
  1428. } else {
  1429. colorAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( colors, 3 ) );
  1430. }
  1431. }
  1432. // normal attribute
  1433. if ( normal ) {
  1434. if ( normalPerVertex === false ) {
  1435. for ( var i = 0; i < xDimension - 1; i ++ ) {
  1436. for ( var j = 0; j < zDimension - 1; j ++ ) {
  1437. var index = i + j * ( xDimension - 1 );
  1438. var xn = normal[ index * 3 + 0 ];
  1439. var yn = normal[ index * 3 + 1 ];
  1440. var zn = normal[ index * 3 + 2 ];
  1441. // one normal per quad
  1442. normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn );
  1443. normals.push( xn, yn, zn ); normals.push( xn, yn, zn ); normals.push( xn, yn, zn );
  1444. }
  1445. }
  1446. normalAttribute = new THREE.Float32BufferAttribute( normals, 3 );
  1447. } else {
  1448. normalAttribute = toNonIndexedAttribute( indices, new THREE.Float32BufferAttribute( normals, 3 ) );
  1449. }
  1450. } else {
  1451. normalAttribute = computeNormalAttribute( indices, vertices, creaseAngle );
  1452. }
  1453. // build geometry
  1454. var geometry = new THREE.BufferGeometry();
  1455. geometry.setAttribute( 'position', positionAttribute );
  1456. geometry.setAttribute( 'normal', normalAttribute );
  1457. geometry.setAttribute( 'uv', uvAttribute );
  1458. if ( colorAttribute ) geometry.setAttribute( 'color', colorAttribute );
  1459. // "solid" influences the material so let's store it for later use
  1460. geometry._solid = solid;
  1461. geometry._type = 'mesh';
  1462. return geometry;
  1463. }
  1464. // helper functions
  1465. function resolveUSE( identifier ) {
  1466. var node = nodeMap[ identifier ];
  1467. var build = getNode( node );
  1468. // because the same 3D objects can have different transformations, it's necessary to clone them.
  1469. // materials can be influenced by the geometry (e.g. vertex normals). cloning is necessary to avoid
  1470. // any side effects
  1471. return ( build.isObject3D || build.isMaterial ) ? build.clone() : build;
  1472. }
  1473. function parseFieldChildren( children, owner ) {
  1474. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1475. var object = getNode( children[ i ] );
  1476. if ( object instanceof THREE.Object3D ) owner.add( object );
  1477. }
  1478. }
  1479. function triangulateFaceIndex( index, ccw ) {
  1480. var indices = [];
  1481. // since face defintions can have more than three vertices, it's necessary to
  1482. // perform a simple triangulation
  1483. var start = 0;
  1484. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1485. var i1 = index[ start ];
  1486. var i2 = index[ i + ( ccw ? 1 : 2 ) ];
  1487. var i3 = index[ i + ( ccw ? 2 : 1 ) ];
  1488. indices.push( i1, i2, i3 );
  1489. // an index of -1 indicates that the current face has ended and the next one begins
  1490. if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
  1491. i += 3;
  1492. start = i + 1;
  1493. }
  1494. }
  1495. return indices;
  1496. }
  1497. function triangulateFaceData( data, index ) {
  1498. var triangulatedData = [];
  1499. var start = 0;
  1500. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1501. var stride = start * 3;
  1502. var x = data[ stride ];
  1503. var y = data[ stride + 1 ];
  1504. var z = data[ stride + 2 ];
  1505. triangulatedData.push( x, y, z );
  1506. // an index of -1 indicates that the current face has ended and the next one begins
  1507. if ( index[ i + 3 ] === - 1 || i + 3 >= l ) {
  1508. i += 3;
  1509. start ++;
  1510. }
  1511. }
  1512. return triangulatedData;
  1513. }
  1514. function flattenData( data, index ) {
  1515. var flattenData = [];
  1516. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1517. var i1 = index[ i ];
  1518. var stride = i1 * 3;
  1519. var x = data[ stride ];
  1520. var y = data[ stride + 1 ];
  1521. var z = data[ stride + 2 ];
  1522. flattenData.push( x, y, z );
  1523. }
  1524. return flattenData;
  1525. }
  1526. function expandLineIndex( index ) {
  1527. var indices = [];
  1528. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1529. var i1 = index[ i ];
  1530. var i2 = index[ i + 1 ];
  1531. indices.push( i1, i2 );
  1532. // an index of -1 indicates that the current line has ended and the next one begins
  1533. if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
  1534. i += 2;
  1535. }
  1536. }
  1537. return indices;
  1538. }
  1539. function expandLineData( data, index ) {
  1540. var triangulatedData = [];
  1541. var start = 0;
  1542. for ( var i = 0, l = index.length; i < l; i ++ ) {
  1543. var stride = start * 3;
  1544. var x = data[ stride ];
  1545. var y = data[ stride + 1 ];
  1546. var z = data[ stride + 2 ];
  1547. triangulatedData.push( x, y, z );
  1548. // an index of -1 indicates that the current line has ended and the next one begins
  1549. if ( index[ i + 2 ] === - 1 || i + 2 >= l ) {
  1550. i += 2;
  1551. start ++;
  1552. }
  1553. }
  1554. return triangulatedData;
  1555. }
  1556. var vA = new THREE.Vector3();
  1557. var vB = new THREE.Vector3();
  1558. var vC = new THREE.Vector3();
  1559. var uvA = new THREE.Vector2();
  1560. var uvB = new THREE.Vector2();
  1561. var uvC = new THREE.Vector2();
  1562. function computeAttributeFromIndexedData( coordIndex, index, data, itemSize ) {
  1563. var array = [];
  1564. // we use the coordIndex.length as delimiter since normalIndex must contain at least as many indices
  1565. for ( var i = 0, l = coordIndex.length; i < l; i += 3 ) {
  1566. var a = index[ i ];
  1567. var b = index[ i + 1 ];
  1568. var c = index[ i + 2 ];
  1569. if ( itemSize === 2 ) {
  1570. uvA.fromArray( data, a * itemSize );
  1571. uvB.fromArray( data, b * itemSize );
  1572. uvC.fromArray( data, c * itemSize );
  1573. array.push( uvA.x, uvA.y );
  1574. array.push( uvB.x, uvB.y );
  1575. array.push( uvC.x, uvC.y );
  1576. } else {
  1577. vA.fromArray( data, a * itemSize );
  1578. vB.fromArray( data, b * itemSize );
  1579. vC.fromArray( data, c * itemSize );
  1580. array.push( vA.x, vA.y, vA.z );
  1581. array.push( vB.x, vB.y, vB.z );
  1582. array.push( vC.x, vC.y, vC.z );
  1583. }
  1584. }
  1585. return new THREE.Float32BufferAttribute( array, itemSize );
  1586. }
  1587. function computeAttributeFromFaceData( index, faceData ) {
  1588. var array = [];
  1589. for ( var i = 0, j = 0, l = index.length; i < l; i += 3, j ++ ) {
  1590. vA.fromArray( faceData, j * 3 );
  1591. array.push( vA.x, vA.y, vA.z );
  1592. array.push( vA.x, vA.y, vA.z );
  1593. array.push( vA.x, vA.y, vA.z );
  1594. }
  1595. return new THREE.Float32BufferAttribute( array, 3 );
  1596. }
  1597. function computeAttributeFromLineData( index, lineData ) {
  1598. var array = [];
  1599. for ( var i = 0, j = 0, l = index.length; i < l; i += 2, j ++ ) {
  1600. vA.fromArray( lineData, j * 3 );
  1601. array.push( vA.x, vA.y, vA.z );
  1602. array.push( vA.x, vA.y, vA.z );
  1603. }
  1604. return new THREE.Float32BufferAttribute( array, 3 );
  1605. }
  1606. function toNonIndexedAttribute( indices, attribute ) {
  1607. var array = attribute.array;
  1608. var itemSize = attribute.itemSize;
  1609. var array2 = new array.constructor( indices.length * itemSize );
  1610. var index = 0, index2 = 0;
  1611. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  1612. index = indices[ i ] * itemSize;
  1613. for ( var j = 0; j < itemSize; j ++ ) {
  1614. array2[ index2 ++ ] = array[ index ++ ];
  1615. }
  1616. }
  1617. return new THREE.Float32BufferAttribute( array2, itemSize );
  1618. }
  1619. var ab = new THREE.Vector3();
  1620. var cb = new THREE.Vector3();
  1621. function computeNormalAttribute( index, coord, creaseAngle ) {
  1622. var faces = [];
  1623. var vertexNormals = {};
  1624. // prepare face and raw vertex normals
  1625. for ( var i = 0, l = index.length; i < l; i += 3 ) {
  1626. var a = index[ i ];
  1627. var b = index[ i + 1 ];
  1628. var c = index[ i + 2 ];
  1629. var face = new Face( a, b, c );
  1630. vA.fromArray( coord, a * 3 );
  1631. vB.fromArray( coord, b * 3 );
  1632. vC.fromArray( coord, c * 3 );
  1633. cb.subVectors( vC, vB );
  1634. ab.subVectors( vA, vB );
  1635. cb.cross( ab );
  1636. cb.normalize();
  1637. face.normal.copy( cb );
  1638. if ( vertexNormals[ a ] === undefined ) vertexNormals[ a ] = [];
  1639. if ( vertexNormals[ b ] === undefined ) vertexNormals[ b ] = [];
  1640. if ( vertexNormals[ c ] === undefined ) vertexNormals[ c ] = [];
  1641. vertexNormals[ a ].push( face.normal );
  1642. vertexNormals[ b ].push( face.normal );
  1643. vertexNormals[ c ].push( face.normal );
  1644. faces.push( face );
  1645. }
  1646. // compute vertex normals and build final geometry
  1647. var normals = [];
  1648. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  1649. var face = faces[ i ];
  1650. var nA = weightedNormal( vertexNormals[ face.a ], face.normal, creaseAngle );
  1651. var nB = weightedNormal( vertexNormals[ face.b ], face.normal, creaseAngle );
  1652. var nC = weightedNormal( vertexNormals[ face.c ], face.normal, creaseAngle );
  1653. vA.fromArray( coord, face.a * 3 );
  1654. vB.fromArray( coord, face.b * 3 );
  1655. vC.fromArray( coord, face.c * 3 );
  1656. normals.push( nA.x, nA.y, nA.z );
  1657. normals.push( nB.x, nB.y, nB.z );
  1658. normals.push( nC.x, nC.y, nC.z );
  1659. }
  1660. return new THREE.Float32BufferAttribute( normals, 3 );
  1661. }
  1662. function weightedNormal( normals, vector, creaseAngle ) {
  1663. var normal = new THREE.Vector3();
  1664. if ( creaseAngle === 0 ) {
  1665. normal.copy( vector );
  1666. } else {
  1667. for ( var i = 0, l = normals.length; i < l; i ++ ) {
  1668. if ( normals[ i ].angleTo( vector ) < creaseAngle ) {
  1669. normal.add( normals[ i ] );
  1670. }
  1671. }
  1672. }
  1673. return normal.normalize();
  1674. }
  1675. function toColorArray( colors ) {
  1676. var array = [];
  1677. for ( var i = 0, l = colors.length; i < l; i += 3 ) {
  1678. array.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  1679. }
  1680. return array;
  1681. }
  1682. /**
  1683. * Vertically paints the faces interpolating between the
  1684. * specified colors at the specified angels. This is used for the Background
  1685. * node, but could be applied to other nodes with multiple faces as well.
  1686. *
  1687. * When used with the Background node, default is directionIsDown is true if
  1688. * interpolating the skyColor down from the Zenith. When interpolationg up from
  1689. * the Nadir i.e. interpolating the groundColor, the directionIsDown is false.
  1690. *
  1691. * The first angle is never specified, it is the Zenith (0 rad). Angles are specified
  1692. * in radians. The geometry is thought a sphere, but could be anything. The color interpolation
  1693. * is linear along the Y axis in any case.
  1694. *
  1695. * You must specify one more color than you have angles at the beginning of the colors array.
  1696. * This is the color of the Zenith (the top of the shape).
  1697. *
  1698. * @param {BufferGeometry} geometry
  1699. * @param {number} radius
  1700. * @param {array} angles
  1701. * @param {array} colors
  1702. * @param {boolean} topDown - Whether to work top down or bottom up.
  1703. */
  1704. function paintFaces( geometry, radius, angles, colors, topDown ) {
  1705. // compute threshold values
  1706. var thresholds = [];
  1707. var startAngle = ( topDown === true ) ? 0 : Math.PI;
  1708. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  1709. var angle = ( i === 0 ) ? 0 : angles[ i - 1 ];
  1710. angle = ( topDown === true ) ? angle : ( startAngle - angle );
  1711. var point = new THREE.Vector3();
  1712. point.setFromSphericalCoords( radius, angle, 0 );
  1713. thresholds.push( point );
  1714. }
  1715. // generate vertex colors
  1716. var indices = geometry.index;
  1717. var positionAttribute = geometry.attributes.position;
  1718. var colorAttribute = new THREE.BufferAttribute( new Float32Array( geometry.attributes.position.count * 3 ), 3 );
  1719. var position = new THREE.Vector3();
  1720. var color = new THREE.Color();
  1721. for ( var i = 0; i < indices.count; i ++ ) {
  1722. var index = indices.getX( i );
  1723. position.fromBufferAttribute( positionAttribute, index );
  1724. var thresholdIndexA, thresholdIndexB;
  1725. var t = 1;
  1726. for ( var j = 1; j < thresholds.length; j ++ ) {
  1727. thresholdIndexA = j - 1;
  1728. thresholdIndexB = j;
  1729. var thresholdA = thresholds[ thresholdIndexA ];
  1730. var thresholdB = thresholds[ thresholdIndexB ];
  1731. if ( topDown === true ) {
  1732. // interpolation for sky color
  1733. if ( position.y <= thresholdA.y && position.y > thresholdB.y ) {
  1734. t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y );
  1735. break;
  1736. }
  1737. } else {
  1738. // interpolation for ground color
  1739. if ( position.y >= thresholdA.y && position.y < thresholdB.y ) {
  1740. t = Math.abs( thresholdA.y - position.y ) / Math.abs( thresholdA.y - thresholdB.y );
  1741. break;
  1742. }
  1743. }
  1744. }
  1745. var colorA = colors[ thresholdIndexA ];
  1746. var colorB = colors[ thresholdIndexB ];
  1747. color.copy( colorA ).lerp( colorB, t );
  1748. colorAttribute.setXYZ( index, color.r, color.g, color.b );
  1749. }
  1750. geometry.setAttribute( 'color', colorAttribute );
  1751. }
  1752. //
  1753. var textureLoader = new THREE.TextureLoader( this.manager );
  1754. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  1755. // create JSON representing the tree structure of the VRML asset
  1756. var tree = generateVRMLTree( data );
  1757. // check version (only 2.0 is supported)
  1758. if ( tree.version.indexOf( 'V2.0' ) === - 1 ) {
  1759. throw Error( 'THREE.VRMLLexer: Version of VRML asset not supported.' );
  1760. }
  1761. // parse the tree structure to a three.js scene
  1762. var scene = parseTree( tree );
  1763. return scene;
  1764. }
  1765. } );
  1766. function VRMLLexer( tokens ) {
  1767. this.lexer = new chevrotain.Lexer( tokens );
  1768. }
  1769. VRMLLexer.prototype = {
  1770. constructor: VRMLLexer,
  1771. lex: function ( inputText ) {
  1772. var lexingResult = this.lexer.tokenize( inputText );
  1773. if ( lexingResult.errors.length > 0 ) {
  1774. console.error( lexingResult.errors );
  1775. throw Error( 'THREE.VRMLLexer: Lexing errors detected.' );
  1776. }
  1777. return lexingResult;
  1778. }
  1779. };
  1780. function VRMLParser( tokenVocabulary ) {
  1781. chevrotain.Parser.call( this, tokenVocabulary );
  1782. var $ = this;
  1783. var Version = tokenVocabulary[ 'Version' ];
  1784. var LCurly = tokenVocabulary[ 'LCurly' ];
  1785. var RCurly = tokenVocabulary[ 'RCurly' ];
  1786. var LSquare = tokenVocabulary[ 'LSquare' ];
  1787. var RSquare = tokenVocabulary[ 'RSquare' ];
  1788. var Identifier = tokenVocabulary[ 'Identifier' ];
  1789. var RouteIdentifier = tokenVocabulary[ 'RouteIdentifier' ];
  1790. var StringLiteral = tokenVocabulary[ 'StringLiteral' ];
  1791. var HexLiteral = tokenVocabulary[ 'HexLiteral' ];
  1792. var NumberLiteral = tokenVocabulary[ 'NumberLiteral' ];
  1793. var TrueLiteral = tokenVocabulary[ 'TrueLiteral' ];
  1794. var FalseLiteral = tokenVocabulary[ 'FalseLiteral' ];
  1795. var NullLiteral = tokenVocabulary[ 'NullLiteral' ];
  1796. var DEF = tokenVocabulary[ 'DEF' ];
  1797. var USE = tokenVocabulary[ 'USE' ];
  1798. var ROUTE = tokenVocabulary[ 'ROUTE' ];
  1799. var TO = tokenVocabulary[ 'TO' ];
  1800. var NodeName = tokenVocabulary[ 'NodeName' ];
  1801. $.RULE( 'vrml', function () {
  1802. $.SUBRULE( $.version );
  1803. $.AT_LEAST_ONE( function () {
  1804. $.SUBRULE( $.node );
  1805. } );
  1806. $.MANY( function () {
  1807. $.SUBRULE( $.route );
  1808. } );
  1809. } );
  1810. $.RULE( 'version', function () {
  1811. $.CONSUME( Version );
  1812. } );
  1813. $.RULE( 'node', function () {
  1814. $.OPTION( function () {
  1815. $.SUBRULE( $.def );
  1816. } );
  1817. $.CONSUME( NodeName );
  1818. $.CONSUME( LCurly );
  1819. $.MANY( function () {
  1820. $.SUBRULE( $.field );
  1821. } );
  1822. $.CONSUME( RCurly );
  1823. } );
  1824. $.RULE( 'field', function () {
  1825. $.CONSUME( Identifier );
  1826. $.OR2( [
  1827. { ALT: function () {
  1828. $.SUBRULE( $.singleFieldValue );
  1829. } },
  1830. { ALT: function () {
  1831. $.SUBRULE( $.multiFieldValue );
  1832. } }
  1833. ] );
  1834. } );
  1835. $.RULE( 'def', function () {
  1836. $.CONSUME( DEF );
  1837. $.OR( [
  1838. { ALT: function () {
  1839. $.CONSUME( Identifier );
  1840. } },
  1841. { ALT: function () {
  1842. $.CONSUME( NodeName );
  1843. } }
  1844. ] );
  1845. } );
  1846. $.RULE( 'use', function () {
  1847. $.CONSUME( USE );
  1848. $.OR( [
  1849. { ALT: function () {
  1850. $.CONSUME( Identifier );
  1851. } },
  1852. { ALT: function () {
  1853. $.CONSUME( NodeName );
  1854. } }
  1855. ] );
  1856. } );
  1857. $.RULE( 'singleFieldValue', function () {
  1858. $.AT_LEAST_ONE( function () {
  1859. $.OR( [
  1860. { ALT: function () {
  1861. $.SUBRULE( $.node );
  1862. } },
  1863. { ALT: function () {
  1864. $.SUBRULE( $.use );
  1865. } },
  1866. { ALT: function () {
  1867. $.CONSUME( StringLiteral );
  1868. } },
  1869. { ALT: function () {
  1870. $.CONSUME( HexLiteral );
  1871. } },
  1872. { ALT: function () {
  1873. $.CONSUME( NumberLiteral );
  1874. } },
  1875. { ALT: function () {
  1876. $.CONSUME( TrueLiteral );
  1877. } },
  1878. { ALT: function () {
  1879. $.CONSUME( FalseLiteral );
  1880. } },
  1881. { ALT: function () {
  1882. $.CONSUME( NullLiteral );
  1883. } }
  1884. ] );
  1885. } );
  1886. } );
  1887. $.RULE( 'multiFieldValue', function () {
  1888. $.CONSUME( LSquare );
  1889. $.MANY( function () {
  1890. $.OR( [
  1891. { ALT: function () {
  1892. $.SUBRULE( $.node );
  1893. } },
  1894. { ALT: function () {
  1895. $.SUBRULE( $.use );
  1896. } },
  1897. { ALT: function () {
  1898. $.CONSUME( StringLiteral );
  1899. } },
  1900. { ALT: function () {
  1901. $.CONSUME( HexLiteral );
  1902. } },
  1903. { ALT: function () {
  1904. $.CONSUME( NumberLiteral );
  1905. } },
  1906. { ALT: function () {
  1907. $.CONSUME( NullLiteral );
  1908. } }
  1909. ] );
  1910. } );
  1911. $.CONSUME( RSquare );
  1912. } );
  1913. $.RULE( 'route', function () {
  1914. $.CONSUME( ROUTE );
  1915. $.CONSUME( RouteIdentifier );
  1916. $.CONSUME( TO );
  1917. $.CONSUME2( RouteIdentifier );
  1918. } );
  1919. this.performSelfAnalysis();
  1920. }
  1921. VRMLParser.prototype = Object.create( chevrotain.Parser.prototype );
  1922. VRMLParser.prototype.constructor = VRMLParser;
  1923. function Face( a, b, c ) {
  1924. this.a = a;
  1925. this.b = b;
  1926. this.c = c;
  1927. this.normal = new THREE.Vector3();
  1928. }
  1929. var TEXTURE_TYPE = {
  1930. INTENSITY: 1,
  1931. INTENSITY_ALPHA: 2,
  1932. RGB: 3,
  1933. RGBA: 4
  1934. };
  1935. return VRMLLoader;
  1936. } )();