LDrawLoader.js 44 KB

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