LDrawLoader.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author yomboprime / https://github.com/yomboprime/
  4. *
  5. *
  6. */
  7. THREE.LDrawLoader = ( function () {
  8. var optionalLineVertShader = /* glsl */`
  9. attribute vec3 control0;
  10. attribute vec3 control1;
  11. attribute vec3 direction;
  12. varying float discardFlag;
  13. #include <common>
  14. #include <color_pars_vertex>
  15. #include <fog_pars_vertex>
  16. #include <logdepthbuf_pars_vertex>
  17. #include <clipping_planes_pars_vertex>
  18. void main() {
  19. #include <color_vertex>
  20. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  21. gl_Position = projectionMatrix * mvPosition;
  22. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  23. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  24. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  25. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  26. c0.xy = c0.xy / c0.w;
  27. c1.xy = c1.xy / c1.w;
  28. p0.xy = p0.xy / p0.w;
  29. p1.xy = p1.xy / p1.w;
  30. vec2 dir = p1.xy - p0.xy;
  31. vec2 norm = vec2( -dir.y, dir.x );
  32. vec2 c0dir = c0.xy - p1.xy;
  33. vec2 c1dir = c1.xy - p1.xy;
  34. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  35. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  36. if ( sign( d0 ) != sign( d1 ) ) discardFlag = 1.0;
  37. #include <logdepthbuf_vertex>
  38. #include <clipping_planes_vertex>
  39. #include <fog_vertex>
  40. }
  41. `;
  42. var optionalLineFragShader = /* glsl */`
  43. uniform vec3 diffuse;
  44. uniform float opacity;
  45. varying float discardFlag;
  46. #include <common>
  47. #include <color_pars_fragment>
  48. #include <fog_pars_fragment>
  49. #include <logdepthbuf_pars_fragment>
  50. #include <clipping_planes_pars_fragment>
  51. void main() {
  52. if ( discardFlag > 0.5 ) discard;
  53. #include <clipping_planes_fragment>
  54. vec3 outgoingLight = vec3( 0.0 );
  55. vec4 diffuseColor = vec4( diffuse, opacity );
  56. #include <logdepthbuf_fragment>
  57. #include <color_fragment>
  58. outgoingLight = diffuseColor.rgb; // simple shader
  59. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  60. #include <premultiplied_alpha_fragment>
  61. #include <tonemapping_fragment>
  62. #include <encodings_fragment>
  63. #include <fog_fragment>
  64. }
  65. `;
  66. var tempVec0 = new THREE.Vector3();
  67. var tempVec1 = new THREE.Vector3();
  68. function smoothNormals( triangles, lineSegments ) {
  69. function hashVertex( v ) {
  70. // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
  71. // to be smoothed as expected (see minifig arms). The errors between edges
  72. // could be due to matrix multiplication.
  73. var x = ~ ~ ( v.x * 1e2 );
  74. var y = ~ ~ ( v.y * 1e2 );
  75. var z = ~ ~ ( v.z * 1e2 );
  76. return `${ x },${ y },${ z }`;
  77. }
  78. function hashEdge( v0, v1 ) {
  79. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  80. }
  81. var hardEdges = new Set();
  82. var halfEdgeList = {};
  83. var fullHalfEdgeList = {};
  84. var normals = [];
  85. // Save the list of hard edges by hash
  86. for ( var i = 0, l = lineSegments.length; i < l; i ++ ) {
  87. var ls = lineSegments[ i ];
  88. var v0 = ls.v0;
  89. var v1 = ls.v1;
  90. hardEdges.add( hashEdge( v0, v1 ) );
  91. hardEdges.add( hashEdge( v1, v0 ) );
  92. }
  93. // track the half edges associated with each triangle
  94. for ( var i = 0, l = triangles.length; i < l; i ++ ) {
  95. var tri = triangles[ i ];
  96. for ( var i2 = 0, l2 = 3; i2 < l2; i2 ++ ) {
  97. var index = i2;
  98. var next = ( i2 + 1 ) % 3;
  99. var v0 = tri[ `v${ index }` ];
  100. var v1 = tri[ `v${ next }` ];
  101. var hash = hashEdge( v0, v1 );
  102. // don't add the triangle if the edge is supposed to be hard
  103. if ( hardEdges.has( hash ) ) continue;
  104. halfEdgeList[ hash ] = tri;
  105. fullHalfEdgeList[ hash ] = tri;
  106. }
  107. }
  108. // Iterate until we've tried to connect all triangles to share normals
  109. while ( true ) {
  110. // Stop if there are no more triangles left
  111. var halfEdges = Object.keys( halfEdgeList );
  112. if ( halfEdges.length === 0 ) break;
  113. // Exhaustively find all connected triangles
  114. var i = 0;
  115. var queue = [ fullHalfEdgeList[ halfEdges[ 0 ] ] ];
  116. while ( i < queue.length ) {
  117. // initialize all vertex normals in this triangle
  118. var tri = queue[ i ];
  119. i ++;
  120. var faceNormal = tri.faceNormal;
  121. if ( tri.n0 === null ) {
  122. tri.n0 = faceNormal.clone();
  123. normals.push( tri.n0 );
  124. }
  125. if ( tri.n1 === null ) {
  126. tri.n1 = faceNormal.clone();
  127. normals.push( tri.n1 );
  128. }
  129. if ( tri.n2 === null ) {
  130. tri.n2 = faceNormal.clone();
  131. normals.push( tri.n2 );
  132. }
  133. // Check if any edge is connected to another triangle edge
  134. for ( var i2 = 0, l2 = 3; i2 < l2; i2 ++ ) {
  135. var index = i2;
  136. var next = ( i2 + 1 ) % 3;
  137. var v0 = tri[ `v${ index }` ];
  138. var v1 = tri[ `v${ next }` ];
  139. // delete this triangle from the list so it won't be found again
  140. var hash = hashEdge( v0, v1 );
  141. delete halfEdgeList[ hash ];
  142. var reverseHash = hashEdge( v1, v0 );
  143. var otherTri = fullHalfEdgeList[ reverseHash ];
  144. if ( otherTri ) {
  145. // NOTE: If the angle between triangles is > 67.5 degrees then assume it's
  146. // hard edge. There are some cases where the line segments do not line up exactly
  147. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  148. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  149. continue;
  150. }
  151. // if this triangle has already been traversed then it won't be in
  152. // the halfEdgeList. If it has not then add it to the queue and delete
  153. // it so it won't be found again.
  154. if ( reverseHash in halfEdgeList ) {
  155. queue.push( otherTri );
  156. delete halfEdgeList[ reverseHash ];
  157. }
  158. // Find the matching edge in this triangle and copy the normal vector over
  159. for ( var i3 = 0, l3 = 3; i3 < l3; i3 ++ ) {
  160. var otherIndex = i3;
  161. var otherNext = ( i3 + 1 ) % 3;
  162. var otherV0 = otherTri[ `v${ otherIndex }` ];
  163. var otherV1 = otherTri[ `v${ otherNext }` ];
  164. var otherHash = hashEdge( otherV0, otherV1 );
  165. if ( otherHash === reverseHash ) {
  166. otherTri[ `n${ otherIndex }` ] = tri[ `n${ next }` ];
  167. otherTri[ `n${ otherNext }` ] = tri[ `n${ index }` ];
  168. tri[ `n${ next }` ].add( otherTri.faceNormal );
  169. tri[ `n${ index }` ].add( otherTri.faceNormal );
  170. break;
  171. }
  172. }
  173. }
  174. }
  175. }
  176. }
  177. // The normals of each face have been added up so now we average them by normalizing the vector.
  178. for ( var i = 0, l = normals.length; i < l; i ++ ) {
  179. normals[ i ].normalize();
  180. }
  181. }
  182. function isPrimitiveType( type ) {
  183. return /primitive/i.test( type ) || type === 'Subpart';
  184. }
  185. function LineParser( line, lineNumber ) {
  186. this.line = line;
  187. this.lineLength = line.length;
  188. this.currentCharIndex = 0;
  189. this.currentChar = ' ';
  190. this.lineNumber = lineNumber;
  191. }
  192. LineParser.prototype = {
  193. constructor: LineParser,
  194. seekNonSpace: function () {
  195. while ( this.currentCharIndex < this.lineLength ) {
  196. this.currentChar = this.line.charAt( this.currentCharIndex );
  197. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  198. return;
  199. }
  200. this.currentCharIndex ++;
  201. }
  202. },
  203. getToken: function () {
  204. var pos0 = this.currentCharIndex ++;
  205. // Seek space
  206. while ( this.currentCharIndex < this.lineLength ) {
  207. this.currentChar = this.line.charAt( this.currentCharIndex );
  208. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  209. break;
  210. }
  211. this.currentCharIndex ++;
  212. }
  213. var pos1 = this.currentCharIndex;
  214. this.seekNonSpace();
  215. return this.line.substring( pos0, pos1 );
  216. },
  217. getRemainingString: function () {
  218. return this.line.substring( this.currentCharIndex, this.lineLength );
  219. },
  220. isAtTheEnd: function () {
  221. return this.currentCharIndex >= this.lineLength;
  222. },
  223. setToEnd: function () {
  224. this.currentCharIndex = this.lineLength;
  225. },
  226. getLineNumberString: function () {
  227. return this.lineNumber >= 0 ? " at line " + this.lineNumber : "";
  228. }
  229. };
  230. function sortByMaterial( a, b ) {
  231. if ( a.colourCode === b.colourCode ) {
  232. return 0;
  233. }
  234. if ( a.colourCode < b.colourCode ) {
  235. return - 1;
  236. }
  237. return 1;
  238. }
  239. function createObject( elements, elementSize ) {
  240. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  241. // With per face / segment material, implemented with mesh groups and materials array
  242. // Sort the triangles or line segments by colour code to make later the mesh groups
  243. elements.sort( sortByMaterial );
  244. var positions = [];
  245. var normals = [];
  246. var materials = [];
  247. var bufferGeometry = new THREE.BufferGeometry();
  248. var prevMaterial = null;
  249. var index0 = 0;
  250. var numGroupVerts = 0;
  251. for ( var iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  252. var elem = elements[ iElem ];
  253. var v0 = elem.v0;
  254. var v1 = elem.v1;
  255. // Note that LDraw coordinate system is rotated 180 deg. in the X axis w.r.t. Three.js's one
  256. positions.push( v0.x, v0.y, v0.z, v1.x, v1.y, v1.z );
  257. if ( elementSize === 3 ) {
  258. positions.push( elem.v2.x, elem.v2.y, elem.v2.z );
  259. var n0 = elem.n0 || elem.faceNormal;
  260. var n1 = elem.n1 || elem.faceNormal;
  261. var n2 = elem.n2 || elem.faceNormal;
  262. normals.push( n0.x, n0.y, n0.z );
  263. normals.push( n1.x, n1.y, n1.z );
  264. normals.push( n2.x, n2.y, n2.z );
  265. }
  266. if ( prevMaterial !== elem.material ) {
  267. if ( prevMaterial !== null ) {
  268. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  269. }
  270. materials.push( elem.material );
  271. prevMaterial = elem.material;
  272. index0 = iElem * elementSize;
  273. numGroupVerts = elementSize;
  274. } else {
  275. numGroupVerts += elementSize;
  276. }
  277. }
  278. if ( numGroupVerts > 0 ) {
  279. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  280. }
  281. bufferGeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  282. if ( elementSize === 3 ) {
  283. bufferGeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  284. }
  285. var object3d = null;
  286. if ( elementSize === 2 ) {
  287. object3d = new THREE.LineSegments( bufferGeometry, materials );
  288. } else if ( elementSize === 3 ) {
  289. object3d = new THREE.Mesh( bufferGeometry, materials );
  290. }
  291. return object3d;
  292. }
  293. //
  294. function LDrawLoader( manager ) {
  295. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  296. // This is a stack of 'parse scopes' with one level per subobject loaded file.
  297. // Each level contains a material lib and also other runtime variables passed between parent and child subobjects
  298. // When searching for a material code, the stack is read from top of the stack to bottom
  299. // Each material library is an object map keyed by colour codes.
  300. this.parseScopesStack = null;
  301. this.path = '';
  302. // Array of THREE.Material
  303. this.materials = [];
  304. // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  305. // This also allows to handle the embedded text files ("0 FILE" lines)
  306. this.subobjectCache = {};
  307. // This object is a map from file names to paths. It agilizes the paths search. If it is not set then files will be searched by trial and error.
  308. this.fileMap = null;
  309. // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  310. this.setMaterials( [
  311. this.parseColourMetaDirective( new LineParser( "Main_Colour CODE 16 VALUE #FF8080 EDGE #333333" ) ),
  312. this.parseColourMetaDirective( new LineParser( "Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333" ) )
  313. ] );
  314. // If this flag is set to true, each subobject will be a THREE.Object.
  315. // If not (the default), only one object which contains all the merged primitives will be created.
  316. this.separateObjects = false;
  317. // If this flag is set to true the vertex normals will be smoothed.
  318. this.smoothNormals = true;
  319. }
  320. // Special surface finish tag types.
  321. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  322. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  323. LDrawLoader.FINISH_TYPE_CHROME = 1;
  324. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  325. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  326. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  327. LDrawLoader.FINISH_TYPE_METAL = 5;
  328. // State machine to search a subobject path.
  329. // The LDraw standard establishes these various possible subfolders.
  330. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  331. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  332. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  333. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  334. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  335. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  336. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  337. LDrawLoader.prototype = {
  338. constructor: LDrawLoader,
  339. load: function ( url, onLoad, onProgress, onError ) {
  340. if ( ! this.fileMap ) {
  341. this.fileMap = {};
  342. }
  343. var scope = this;
  344. var fileLoader = new THREE.FileLoader( this.manager );
  345. fileLoader.setPath( this.path );
  346. fileLoader.load( url, function ( text ) {
  347. processObject( text, onLoad );
  348. }, onProgress, onError );
  349. function processObject( text, onProcessed, subobject ) {
  350. var parseScope = scope.newParseScopeLevel();
  351. parseScope.url = url;
  352. var parentParseScope = scope.getParentParseScope();
  353. // Set current matrix
  354. if ( subobject ) {
  355. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  356. parseScope.matrix.copy( subobject.matrix );
  357. parseScope.inverted = subobject.inverted;
  358. }
  359. // Add to cache
  360. var currentFileName = parentParseScope.currentFileName;
  361. if ( currentFileName !== null ) {
  362. currentFileName = parentParseScope.currentFileName.toLowerCase();
  363. }
  364. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  365. scope.subobjectCache[ currentFileName ] = text;
  366. }
  367. // Parse the object (returns a THREE.Group)
  368. scope.parse( text );
  369. var finishedCount = 0;
  370. onSubobjectFinish();
  371. function onSubobjectFinish() {
  372. finishedCount ++;
  373. if ( finishedCount === parseScope.subobjects.length + 1 ) {
  374. finalizeObject();
  375. } else {
  376. // Once the previous subobject has finished we can start processing the next one in the list.
  377. // The subobject processing shares scope in processing so it's important that they be loaded serially
  378. // to avoid race conditions.
  379. // Promise.resolve is used as an approach to asynchronously schedule a task _before_ this frame ends to
  380. // avoid stack overflow exceptions when loading many subobjects from the cache. RequestAnimationFrame
  381. // will work but causes the load to happen after the next frame which causes the load to take significantly longer.
  382. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  383. Promise.resolve().then( function () {
  384. loadSubobject( subobject );
  385. } );
  386. parseScope.subobjectIndex ++;
  387. }
  388. }
  389. function finalizeObject() {
  390. if ( scope.smoothNormals && parseScope.type === 'Part' ) {
  391. smoothNormals( parseScope.triangles, parseScope.lineSegments );
  392. }
  393. var isRoot = ! parentParseScope.isFromParse;
  394. if ( scope.separateObjects && ! isPrimitiveType( parseScope.type ) || isRoot ) {
  395. const objGroup = parseScope.groupObject;
  396. if ( parseScope.triangles.length > 0 ) {
  397. objGroup.add( createObject( parseScope.triangles, 3 ) );
  398. }
  399. if ( parseScope.lineSegments.length > 0 ) {
  400. objGroup.add( createObject( parseScope.lineSegments, 2 ) );
  401. }
  402. if ( parseScope.conditionalSegments.length > 0 ) {
  403. var conditionalSegments = parseScope.conditionalSegments;
  404. var lines = createObject( conditionalSegments, 2 );
  405. lines.isConditionalLine = true;
  406. var controlArray0 = new Float32Array( conditionalSegments.length * 3 * 2 );
  407. var controlArray1 = new Float32Array( conditionalSegments.length * 3 * 2 );
  408. var directionArray = new Float32Array( conditionalSegments.length * 3 * 2 );
  409. for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  410. var os = conditionalSegments[ i ];
  411. var c0 = os.c0;
  412. var c1 = os.c1;
  413. var v0 = os.v0;
  414. var v1 = os.v1;
  415. var index = i * 3 * 2;
  416. controlArray0[ index + 0 ] = c0.x;
  417. controlArray0[ index + 1 ] = c0.y;
  418. controlArray0[ index + 2 ] = c0.z;
  419. controlArray0[ index + 3 ] = c0.x;
  420. controlArray0[ index + 4 ] = c0.y;
  421. controlArray0[ index + 5 ] = c0.z;
  422. controlArray1[ index + 0 ] = c1.x;
  423. controlArray1[ index + 1 ] = c1.y;
  424. controlArray1[ index + 2 ] = c1.z;
  425. controlArray1[ index + 3 ] = c1.x;
  426. controlArray1[ index + 4 ] = c1.y;
  427. controlArray1[ index + 5 ] = c1.z;
  428. directionArray[ index + 0 ] = v1.x - v0.x;
  429. directionArray[ index + 1 ] = v1.y - v0.y;
  430. directionArray[ index + 2 ] = v1.z - v0.z;
  431. directionArray[ index + 3 ] = v1.x - v0.x;
  432. directionArray[ index + 4 ] = v1.y - v0.y;
  433. directionArray[ index + 5 ] = v1.z - v0.z;
  434. }
  435. lines.geometry.addAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  436. lines.geometry.addAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  437. lines.geometry.addAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  438. lines.material = lines.material.map( mat => {
  439. return new THREE.ShaderMaterial( {
  440. vertexShader: optionalLineVertShader,
  441. fragmentShader: optionalLineFragShader,
  442. uniforms: {
  443. diffuse: {
  444. value: mat.color
  445. },
  446. opacity: {
  447. value: mat.opacity
  448. }
  449. }
  450. } );
  451. } );
  452. objGroup.add( lines );
  453. }
  454. if ( parentParseScope.groupObject ) {
  455. objGroup.name = parseScope.fileName;
  456. objGroup.userData.category = parseScope.category;
  457. objGroup.userData.keywords = parseScope.keywords;
  458. parseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  459. parentParseScope.groupObject.add( objGroup );
  460. }
  461. } else {
  462. var separateObjects = scope.separateObjects;
  463. var parentLineSegments = parentParseScope.lineSegments;
  464. var parentConditionalSegments = parentParseScope.conditionalSegments;
  465. var parentTriangles = parentParseScope.triangles;
  466. var lineSegments = parseScope.lineSegments;
  467. var conditionalSegments = parseScope.conditionalSegments;
  468. var triangles = parseScope.triangles;
  469. for ( var i = 0, l = lineSegments.length; i < l; i ++ ) {
  470. var ls = lineSegments[ i ];
  471. if ( separateObjects ) {
  472. ls.v0.applyMatrix4( parseScope.matrix );
  473. ls.v1.applyMatrix4( parseScope.matrix );
  474. }
  475. parentLineSegments.push( ls );
  476. }
  477. for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  478. var os = conditionalSegments[ i ];
  479. if ( separateObjects ) {
  480. os.v0.applyMatrix4( parseScope.matrix );
  481. os.v1.applyMatrix4( parseScope.matrix );
  482. os.c0.applyMatrix4( parseScope.matrix );
  483. os.c1.applyMatrix4( parseScope.matrix );
  484. }
  485. parentConditionalSegments.push( os );
  486. }
  487. for ( var i = 0, l = triangles.length; i < l; i ++ ) {
  488. var tri = triangles[ i ];
  489. if ( separateObjects ) {
  490. tri.v0 = tri.v0.clone().applyMatrix4( parseScope.matrix );
  491. tri.v1 = tri.v1.clone().applyMatrix4( parseScope.matrix );
  492. tri.v2 = tri.v2.clone().applyMatrix4( parseScope.matrix );
  493. tempVec0.subVectors( tri.v1, tri.v0 );
  494. tempVec1.subVectors( tri.v2, tri.v1 );
  495. tri.faceNormal.crossVectors( tempVec0, tempVec1 ).normalize();
  496. }
  497. parentTriangles.push( tri );
  498. }
  499. }
  500. scope.removeScopeLevel();
  501. if ( onProcessed ) {
  502. onProcessed( parseScope.groupObject );
  503. }
  504. }
  505. function loadSubobject( subobject ) {
  506. parseScope.mainColourCode = subobject.material.userData.code;
  507. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  508. parseScope.currentFileName = subobject.originalFileName;
  509. // If subobject was cached previously, use the cached one
  510. var cached = scope.subobjectCache[ subobject.originalFileName.toLowerCase() ];
  511. if ( cached ) {
  512. processObject( cached, function ( subobjectGroup ) {
  513. onSubobjectLoaded( subobjectGroup, subobject );
  514. onSubobjectFinish();
  515. }, subobject );
  516. return;
  517. }
  518. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  519. // Update also subobject.locationState for the next try if this load fails.
  520. var subobjectURL = subobject.fileName;
  521. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  522. switch ( subobject.locationState ) {
  523. case LDrawLoader.FILE_LOCATION_AS_IS:
  524. newLocationState = subobject.locationState + 1;
  525. break;
  526. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  527. subobjectURL = 'parts/' + subobjectURL;
  528. newLocationState = subobject.locationState + 1;
  529. break;
  530. case LDrawLoader.FILE_LOCATION_TRY_P:
  531. subobjectURL = 'p/' + subobjectURL;
  532. newLocationState = subobject.locationState + 1;
  533. break;
  534. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  535. subobjectURL = 'models/' + subobjectURL;
  536. newLocationState = subobject.locationState + 1;
  537. break;
  538. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  539. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  540. newLocationState = subobject.locationState + 1;
  541. break;
  542. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  543. if ( subobject.triedLowerCase ) {
  544. // Try absolute path
  545. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  546. } else {
  547. // Next attempt is lower case
  548. subobject.fileName = subobject.fileName.toLowerCase();
  549. subobjectURL = subobject.fileName;
  550. subobject.triedLowerCase = true;
  551. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  552. }
  553. break;
  554. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  555. // All location possibilities have been tried, give up loading this object
  556. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  557. return;
  558. }
  559. subobject.locationState = newLocationState;
  560. subobject.url = subobjectURL;
  561. // Load the subobject
  562. // Use another file loader here so we can keep track of the subobject information
  563. // and use it when processing the next model.
  564. var fileLoader = new THREE.FileLoader( scope.manager );
  565. fileLoader.setPath( scope.path );
  566. fileLoader.load( subobjectURL, function ( text ) {
  567. processObject( text, function ( subobjectGroup ) {
  568. onSubobjectLoaded( subobjectGroup, subobject );
  569. onSubobjectFinish();
  570. }, subobject );
  571. }, undefined, function ( err ) {
  572. onSubobjectError( err, subobject );
  573. }, subobject );
  574. }
  575. function onSubobjectLoaded( subobjectGroup, subobject ) {
  576. if ( subobjectGroup === null ) {
  577. // Try to reload
  578. loadSubobject( subobject );
  579. return;
  580. }
  581. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  582. }
  583. function onSubobjectError( err, subobject ) {
  584. // Retry download from a different default possible location
  585. loadSubobject( subobject );
  586. }
  587. }
  588. },
  589. setPath: function ( value ) {
  590. this.path = value;
  591. return this;
  592. },
  593. setMaterials: function ( materials ) {
  594. // Clears parse scopes stack, adds new scope with material library
  595. this.parseScopesStack = [];
  596. this.newParseScopeLevel( materials );
  597. this.getCurrentParseScope().isFromParse = false;
  598. this.materials = materials;
  599. return this;
  600. },
  601. setFileMap: function ( fileMap ) {
  602. this.fileMap = fileMap;
  603. return this;
  604. },
  605. newParseScopeLevel: function ( materials ) {
  606. // Adds a new scope level, assign materials to it and returns it
  607. var matLib = {};
  608. if ( materials ) {
  609. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  610. var material = materials[ i ];
  611. matLib[ material.userData.code ] = material;
  612. }
  613. }
  614. var topParseScope = this.getCurrentParseScope();
  615. var newParseScope = {
  616. lib: matLib,
  617. url: null,
  618. // Subobjects
  619. subobjects: null,
  620. numSubobjects: 0,
  621. subobjectIndex: 0,
  622. inverted: false,
  623. category: null,
  624. keywords: null,
  625. // Current subobject
  626. currentFileName: null,
  627. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  628. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  629. currentMatrix: new THREE.Matrix4(),
  630. matrix: new THREE.Matrix4(),
  631. // If false, it is a root material scope previous to parse
  632. isFromParse: true,
  633. triangles: null,
  634. lineSegments: null,
  635. conditionalSegments: null,
  636. };
  637. this.parseScopesStack.push( newParseScope );
  638. return newParseScope;
  639. },
  640. removeScopeLevel: function () {
  641. this.parseScopesStack.pop();
  642. return this;
  643. },
  644. addMaterial: function ( material ) {
  645. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  646. var matLib = this.getCurrentParseScope().lib;
  647. if ( ! matLib[ material.userData.code ] ) {
  648. this.materials.push( material );
  649. }
  650. matLib[ material.userData.code ] = material;
  651. return this;
  652. },
  653. getMaterial: function ( colourCode ) {
  654. // Given a colour code search its material in the parse scopes stack
  655. if ( colourCode.startsWith( "0x2" ) ) {
  656. // Special 'direct' material value (RGB colour)
  657. var colour = colourCode.substring( 3 );
  658. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  659. }
  660. for ( var i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  661. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  662. if ( material ) {
  663. return material;
  664. }
  665. }
  666. // Material was not found
  667. return null;
  668. },
  669. getParentParseScope: function () {
  670. if ( this.parseScopesStack.length > 1 ) {
  671. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  672. }
  673. return null;
  674. },
  675. getCurrentParseScope: function () {
  676. if ( this.parseScopesStack.length > 0 ) {
  677. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  678. }
  679. return null;
  680. },
  681. parseColourMetaDirective: function ( lineParser ) {
  682. // Parses a colour definition and returns a THREE.Material or null if error
  683. var code = null;
  684. // Triangle and line colours
  685. var colour = 0xFF00FF;
  686. var edgeColour = 0xFF00FF;
  687. // Transparency
  688. var alpha = 1;
  689. var isTransparent = false;
  690. // Self-illumination:
  691. var luminance = 0;
  692. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  693. var canHaveEnvMap = true;
  694. var edgeMaterial = null;
  695. var name = lineParser.getToken();
  696. if ( ! name ) {
  697. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  698. }
  699. // Parse tag tokens and their parameters
  700. var token = null;
  701. while ( true ) {
  702. token = lineParser.getToken();
  703. if ( ! token ) {
  704. break;
  705. }
  706. switch ( token.toUpperCase() ) {
  707. case "CODE":
  708. code = lineParser.getToken();
  709. break;
  710. case "VALUE":
  711. colour = lineParser.getToken();
  712. if ( colour.startsWith( '0x' ) ) {
  713. colour = '#' + colour.substring( 2 );
  714. } else if ( ! colour.startsWith( '#' ) ) {
  715. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  716. }
  717. break;
  718. case "EDGE":
  719. edgeColour = lineParser.getToken();
  720. if ( edgeColour.startsWith( '0x' ) ) {
  721. edgeColour = '#' + edgeColour.substring( 2 );
  722. } else if ( ! edgeColour.startsWith( '#' ) ) {
  723. // Try to see if edge colour is a colour code
  724. edgeMaterial = this.getMaterial( edgeColour );
  725. if ( ! edgeMaterial ) {
  726. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  727. }
  728. // Get the edge material for this triangle material
  729. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  730. }
  731. break;
  732. case 'ALPHA':
  733. alpha = parseInt( lineParser.getToken() );
  734. if ( isNaN( alpha ) ) {
  735. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  736. }
  737. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  738. if ( alpha < 1 ) {
  739. isTransparent = true;
  740. }
  741. break;
  742. case 'LUMINANCE':
  743. luminance = parseInt( lineParser.getToken() );
  744. if ( isNaN( luminance ) ) {
  745. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  746. }
  747. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  748. break;
  749. case 'CHROME':
  750. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  751. break;
  752. case 'PEARLESCENT':
  753. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  754. break;
  755. case 'RUBBER':
  756. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  757. break;
  758. case 'MATTE_METALLIC':
  759. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  760. break;
  761. case 'METAL':
  762. finishType = LDrawLoader.FINISH_TYPE_METAL;
  763. break;
  764. case 'MATERIAL':
  765. // Not implemented
  766. lineParser.setToEnd();
  767. break;
  768. default:
  769. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  770. break;
  771. }
  772. }
  773. var material = null;
  774. switch ( finishType ) {
  775. case LDrawLoader.FINISH_TYPE_DEFAULT:
  776. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.3, envMapIntensity: 0.3, metalness: 0 } );
  777. break;
  778. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  779. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  780. var specular = new THREE.Color( colour );
  781. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  782. hsl.h = ( hsl.h + 0.5 ) % 1;
  783. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  784. specular.setHSL( hsl.h, hsl.s, hsl.l );
  785. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: 10, reflectivity: 0.3 } );
  786. break;
  787. case LDrawLoader.FINISH_TYPE_CHROME:
  788. // Mirror finish surface
  789. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  790. break;
  791. case LDrawLoader.FINISH_TYPE_RUBBER:
  792. // Rubber is best simulated with Lambert
  793. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
  794. canHaveEnvMap = false;
  795. break;
  796. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  797. // Brushed metal finish
  798. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  799. break;
  800. case LDrawLoader.FINISH_TYPE_METAL:
  801. // Average metal finish
  802. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  803. break;
  804. default:
  805. // Should not happen
  806. break;
  807. }
  808. material.transparent = isTransparent;
  809. material.premultipliedAlpha = true;
  810. material.opacity = alpha;
  811. material.polygonOffset = true;
  812. material.polygonOffsetFactor = 1;
  813. material.userData.canHaveEnvMap = canHaveEnvMap;
  814. if ( luminance !== 0 ) {
  815. material.emissive.set( material.color ).multiplyScalar( luminance );
  816. }
  817. if ( ! edgeMaterial ) {
  818. // This is the material used for edges
  819. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  820. edgeMaterial.userData.code = code;
  821. edgeMaterial.name = name + " - Edge";
  822. edgeMaterial.userData.canHaveEnvMap = false;
  823. }
  824. material.userData.code = code;
  825. material.name = name;
  826. material.userData.edgeMaterial = edgeMaterial;
  827. return material;
  828. },
  829. //
  830. parse: function ( text ) {
  831. //console.time( 'LDrawLoader' );
  832. // Retrieve data from the parent parse scope
  833. var parentParseScope = this.getParentParseScope();
  834. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  835. var mainColourCode = parentParseScope.mainColourCode;
  836. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  837. var url = parentParseScope.url;
  838. var currentParseScope = this.getCurrentParseScope();
  839. // Parse result variables
  840. var triangles;
  841. var lineSegments;
  842. var conditionalSegments;
  843. var subobjects = [];
  844. var category = null;
  845. var keywords = null;
  846. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  847. // This is faster than String.split with regex that splits on both
  848. text = text.replace( /\r\n/g, '\n' );
  849. }
  850. var lines = text.split( '\n' );
  851. var numLines = lines.length;
  852. var lineIndex = 0;
  853. var parsingEmbeddedFiles = false;
  854. var currentEmbeddedFileName = null;
  855. var currentEmbeddedText = null;
  856. var bfcCertified = false;
  857. var bfcCCW = true;
  858. var bfcInverted = false;
  859. var bfcCull = true;
  860. var type = '';
  861. var scope = this;
  862. function parseColourCode( lineParser, forEdge ) {
  863. // Parses next colour code and returns a THREE.Material
  864. var colourCode = lineParser.getToken();
  865. if ( ! forEdge && colourCode === '16' ) {
  866. colourCode = mainColourCode;
  867. }
  868. if ( forEdge && colourCode === '24' ) {
  869. colourCode = mainEdgeColourCode;
  870. }
  871. var material = scope.getMaterial( colourCode );
  872. if ( ! material ) {
  873. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  874. }
  875. return material;
  876. }
  877. function parseVector( lp ) {
  878. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  879. if ( ! scope.separateObjects ) {
  880. v.applyMatrix4( currentParseScope.currentMatrix );
  881. }
  882. return v;
  883. }
  884. // Parse all line commands
  885. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  886. var line = lines[ lineIndex ];
  887. if ( line.length === 0 ) continue;
  888. if ( parsingEmbeddedFiles ) {
  889. if ( line.startsWith( '0 FILE ' ) ) {
  890. // Save previous embedded file in the cache
  891. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  892. // New embedded text file
  893. currentEmbeddedFileName = line.substring( 7 );
  894. currentEmbeddedText = '';
  895. } else {
  896. currentEmbeddedText += line + '\n';
  897. }
  898. continue;
  899. }
  900. var lp = new LineParser( line, lineIndex + 1 );
  901. lp.seekNonSpace();
  902. if ( lp.isAtTheEnd() ) {
  903. // Empty line
  904. continue;
  905. }
  906. // Parse the line type
  907. var lineType = lp.getToken();
  908. switch ( lineType ) {
  909. // Line type 0: Comment or META
  910. case '0':
  911. // Parse meta directive
  912. var meta = lp.getToken();
  913. if ( meta ) {
  914. switch ( meta ) {
  915. case '!LDRAW_ORG':
  916. type = lp.getToken();
  917. if ( ! parsingEmbeddedFiles ) {
  918. currentParseScope.triangles = [];
  919. currentParseScope.lineSegments = [];
  920. currentParseScope.conditionalSegments = [];
  921. currentParseScope.type = type;
  922. var isRoot = ! parentParseScope.isFromParse;
  923. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  924. currentParseScope.groupObject = new THREE.Group();
  925. }
  926. // If the scale of the object is negated then the triangle winding order
  927. // needs to be flipped.
  928. var matrix = currentParseScope.matrix;
  929. if (
  930. matrix.determinant() < 0 && (
  931. scope.separateObjects && isPrimitiveType( type ) ||
  932. ! scope.separateObjects
  933. ) ) {
  934. currentParseScope.inverted = ! currentParseScope.inverted;
  935. }
  936. triangles = currentParseScope.triangles;
  937. lineSegments = currentParseScope.lineSegments;
  938. conditionalSegments = currentParseScope.conditionalSegments;
  939. }
  940. break;
  941. case '!COLOUR':
  942. var material = this.parseColourMetaDirective( lp );
  943. if ( material ) {
  944. this.addMaterial( material );
  945. } else {
  946. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  947. }
  948. break;
  949. case '!CATEGORY':
  950. category = lp.getToken();
  951. break;
  952. case '!KEYWORDS':
  953. var newKeywords = lp.getRemainingString().split( ',' );
  954. if ( newKeywords.length > 0 ) {
  955. if ( ! keywords ) {
  956. keywords = [];
  957. }
  958. newKeywords.forEach( function ( keyword ) {
  959. keywords.push( keyword.trim() );
  960. } );
  961. }
  962. break;
  963. case 'FILE':
  964. if ( lineIndex > 0 ) {
  965. // Start embedded text files parsing
  966. parsingEmbeddedFiles = true;
  967. currentEmbeddedFileName = lp.getRemainingString();
  968. currentEmbeddedText = '';
  969. bfcCertified = false;
  970. bfcCCW = true;
  971. }
  972. break;
  973. case 'BFC':
  974. // Changes to the backface culling state
  975. while ( ! lp.isAtTheEnd() ) {
  976. var token = lp.getToken();
  977. switch ( token ) {
  978. case 'CERTIFY':
  979. case 'NOCERTIFY':
  980. bfcCertified = token === 'CERTIFY';
  981. bfcCCW = true;
  982. break;
  983. case 'CW':
  984. case 'CCW':
  985. bfcCCW = token === 'CCW';
  986. break;
  987. case 'INVERTNEXT':
  988. bfcInverted = true;
  989. break;
  990. case 'CLIP':
  991. case 'NOCLIP':
  992. bfcCull = token === 'CLIP';
  993. break;
  994. default:
  995. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  996. break;
  997. }
  998. }
  999. break;
  1000. default:
  1001. // Other meta directives are not implemented
  1002. break;
  1003. }
  1004. }
  1005. break;
  1006. // Line type 1: Sub-object file
  1007. case '1':
  1008. var material = parseColourCode( lp );
  1009. var posX = parseFloat( lp.getToken() );
  1010. var posY = parseFloat( lp.getToken() );
  1011. var posZ = parseFloat( lp.getToken() );
  1012. var m0 = parseFloat( lp.getToken() );
  1013. var m1 = parseFloat( lp.getToken() );
  1014. var m2 = parseFloat( lp.getToken() );
  1015. var m3 = parseFloat( lp.getToken() );
  1016. var m4 = parseFloat( lp.getToken() );
  1017. var m5 = parseFloat( lp.getToken() );
  1018. var m6 = parseFloat( lp.getToken() );
  1019. var m7 = parseFloat( lp.getToken() );
  1020. var m8 = parseFloat( lp.getToken() );
  1021. var matrix = new THREE.Matrix4().set(
  1022. m0, m1, m2, posX,
  1023. m3, m4, m5, posY,
  1024. m6, m7, m8, posZ,
  1025. 0, 0, 0, 1
  1026. );
  1027. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  1028. if ( scope.fileMap[ fileName ] ) {
  1029. // Found the subobject path in the preloaded file path map
  1030. fileName = scope.fileMap[ fileName ];
  1031. } else {
  1032. // Standardized subfolders
  1033. if ( fileName.startsWith( 's/' ) ) {
  1034. fileName = 'parts/' + fileName;
  1035. } else if ( fileName.startsWith( '48/' ) ) {
  1036. fileName = 'p/' + fileName;
  1037. }
  1038. }
  1039. subobjects.push( {
  1040. material: material,
  1041. matrix: matrix,
  1042. fileName: fileName,
  1043. originalFileName: fileName,
  1044. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  1045. url: null,
  1046. triedLowerCase: false,
  1047. inverted: bfcInverted !== currentParseScope.inverted
  1048. } );
  1049. bfcInverted = false;
  1050. break;
  1051. // Line type 2: Line segment
  1052. // Line type 5: Conditional Line segment
  1053. case '2':
  1054. case '5':
  1055. var material = parseColourCode( lp, true );
  1056. var arr = lineType === '2' ? lineSegments : conditionalSegments;
  1057. var segment = {
  1058. material: material.userData.edgeMaterial,
  1059. colourCode: material.userData.code,
  1060. v0: parseVector( lp ),
  1061. v1: parseVector( lp )
  1062. };
  1063. if ( lineType === '5' ) {
  1064. segment.c0 = parseVector( lp );
  1065. segment.c1 = parseVector( lp );
  1066. }
  1067. arr.push( segment );
  1068. break;
  1069. // Line type 3: Triangle
  1070. case '3':
  1071. var material = parseColourCode( lp );
  1072. var inverted = currentParseScope.inverted;
  1073. var ccw = bfcCCW !== inverted;
  1074. var doubleSided = ! bfcCertified || ! bfcCull;
  1075. var v0, v1, v2, faceNormal;
  1076. if ( ccw === true ) {
  1077. v0 = parseVector( lp );
  1078. v1 = parseVector( lp );
  1079. v2 = parseVector( lp );
  1080. } else {
  1081. v2 = parseVector( lp );
  1082. v1 = parseVector( lp );
  1083. v0 = parseVector( lp );
  1084. }
  1085. tempVec0.subVectors( v1, v0 );
  1086. tempVec1.subVectors( v2, v1 );
  1087. faceNormal = new THREE.Vector3()
  1088. .crossVectors( tempVec0, tempVec1 )
  1089. .normalize();
  1090. triangles.push( {
  1091. material: material,
  1092. colourCode: material.userData.code,
  1093. v0: v0,
  1094. v1: v1,
  1095. v2: v2,
  1096. faceNormal: faceNormal,
  1097. n0: null,
  1098. n1: null,
  1099. n2: null
  1100. } );
  1101. if ( doubleSided === true ) {
  1102. triangles.push( {
  1103. material: material,
  1104. colourCode: material.userData.code,
  1105. v0: v0,
  1106. v1: v2,
  1107. v2: v1,
  1108. faceNormal: faceNormal,
  1109. n0: null,
  1110. n1: null,
  1111. n2: null
  1112. } );
  1113. }
  1114. break;
  1115. // Line type 4: Quadrilateral
  1116. case '4':
  1117. var material = parseColourCode( lp );
  1118. var inverted = currentParseScope.inverted;
  1119. var ccw = bfcCCW !== inverted;
  1120. var doubleSided = ! bfcCertified || ! bfcCull;
  1121. var v0, v1, v2, v3, faceNormal;
  1122. if ( ccw === true ) {
  1123. v0 = parseVector( lp );
  1124. v1 = parseVector( lp );
  1125. v2 = parseVector( lp );
  1126. v3 = parseVector( lp );
  1127. } else {
  1128. v3 = parseVector( lp );
  1129. v2 = parseVector( lp );
  1130. v1 = parseVector( lp );
  1131. v0 = parseVector( lp );
  1132. }
  1133. tempVec0.subVectors( v1, v0 );
  1134. tempVec1.subVectors( v2, v1 );
  1135. faceNormal = new THREE.Vector3()
  1136. .crossVectors( tempVec0, tempVec1 )
  1137. .normalize();
  1138. triangles.push( {
  1139. material: material,
  1140. colourCode: material.userData.code,
  1141. v0: v0,
  1142. v1: v1,
  1143. v2: v2,
  1144. faceNormal: faceNormal,
  1145. n0: null,
  1146. n1: null,
  1147. n2: null
  1148. } );
  1149. triangles.push( {
  1150. material: material,
  1151. colourCode: material.userData.code,
  1152. v0: v0,
  1153. v1: v2,
  1154. v2: v3,
  1155. faceNormal: faceNormal,
  1156. n0: null,
  1157. n1: null,
  1158. n2: null
  1159. } );
  1160. if ( doubleSided === true ) {
  1161. triangles.push( {
  1162. material: material,
  1163. colourCode: material.userData.code,
  1164. v0: v0,
  1165. v1: v2,
  1166. v2: v1,
  1167. faceNormal: faceNormal,
  1168. n0: null,
  1169. n1: null,
  1170. n2: null
  1171. } );
  1172. triangles.push( {
  1173. material: material,
  1174. colourCode: material.userData.code,
  1175. v0: v0,
  1176. v1: v3,
  1177. v2: v2,
  1178. faceNormal: faceNormal,
  1179. n0: null,
  1180. n1: null,
  1181. n2: null
  1182. } );
  1183. }
  1184. break;
  1185. default:
  1186. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1187. break;
  1188. }
  1189. }
  1190. if ( parsingEmbeddedFiles ) {
  1191. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  1192. }
  1193. currentParseScope.category = category;
  1194. currentParseScope.keywords = keywords;
  1195. currentParseScope.subobjects = subobjects;
  1196. currentParseScope.numSubobjects = subobjects.length;
  1197. currentParseScope.subobjectIndex = 0;
  1198. }
  1199. };
  1200. return LDrawLoader;
  1201. } )();