LDrawLoader.js 39 KB

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