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