LDrawLoader.js 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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.polygonOffset = true;
  815. material.polygonOffsetFactor = 1;
  816. material.userData.canHaveEnvMap = canHaveEnvMap;
  817. if ( luminance !== 0 ) {
  818. material.emissive.set( material.color ).multiplyScalar( luminance );
  819. }
  820. if ( ! edgeMaterial ) {
  821. // This is the material used for edges
  822. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  823. edgeMaterial.userData.code = code;
  824. edgeMaterial.name = name + " - Edge";
  825. edgeMaterial.userData.canHaveEnvMap = false;
  826. // This is the material used for conditional edges
  827. edgeMaterial.userData.conditionalEdgeMaterial = new THREE.ShaderMaterial( {
  828. vertexShader: conditionalLineVertShader,
  829. fragmentShader: conditionalLineFragShader,
  830. uniforms: {
  831. diffuse: {
  832. value: new THREE.Color( edgeColour )
  833. },
  834. opacity: {
  835. value: alpha
  836. }
  837. }
  838. } );
  839. edgeMaterial.userData.conditionalEdgeMaterial.userData.canHaveEnvMap = false;
  840. }
  841. material.userData.code = code;
  842. material.name = name;
  843. material.userData.edgeMaterial = edgeMaterial;
  844. return material;
  845. },
  846. //
  847. parse: function ( text ) {
  848. //console.time( 'LDrawLoader' );
  849. // Retrieve data from the parent parse scope
  850. var parentParseScope = this.getParentParseScope();
  851. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  852. var mainColourCode = parentParseScope.mainColourCode;
  853. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  854. var url = parentParseScope.url;
  855. var currentParseScope = this.getCurrentParseScope();
  856. // Parse result variables
  857. var triangles;
  858. var lineSegments;
  859. var conditionalSegments;
  860. var subobjects = [];
  861. var category = null;
  862. var keywords = null;
  863. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  864. // This is faster than String.split with regex that splits on both
  865. text = text.replace( /\r\n/g, '\n' );
  866. }
  867. var lines = text.split( '\n' );
  868. var numLines = lines.length;
  869. var lineIndex = 0;
  870. var parsingEmbeddedFiles = false;
  871. var currentEmbeddedFileName = null;
  872. var currentEmbeddedText = null;
  873. var bfcCertified = false;
  874. var bfcCCW = true;
  875. var bfcInverted = false;
  876. var bfcCull = true;
  877. var type = '';
  878. var scope = this;
  879. function parseColourCode( lineParser, forEdge ) {
  880. // Parses next colour code and returns a THREE.Material
  881. var colourCode = lineParser.getToken();
  882. if ( ! forEdge && colourCode === '16' ) {
  883. colourCode = mainColourCode;
  884. }
  885. if ( forEdge && colourCode === '24' ) {
  886. colourCode = mainEdgeColourCode;
  887. }
  888. var material = scope.getMaterial( colourCode );
  889. if ( ! material ) {
  890. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  891. }
  892. return material;
  893. }
  894. function parseVector( lp ) {
  895. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  896. if ( ! scope.separateObjects ) {
  897. v.applyMatrix4( currentParseScope.currentMatrix );
  898. }
  899. return v;
  900. }
  901. // Parse all line commands
  902. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  903. var line = lines[ lineIndex ];
  904. if ( line.length === 0 ) continue;
  905. if ( parsingEmbeddedFiles ) {
  906. if ( line.startsWith( '0 FILE ' ) ) {
  907. // Save previous embedded file in the cache
  908. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  909. // New embedded text file
  910. currentEmbeddedFileName = line.substring( 7 );
  911. currentEmbeddedText = '';
  912. } else {
  913. currentEmbeddedText += line + '\n';
  914. }
  915. continue;
  916. }
  917. var lp = new LineParser( line, lineIndex + 1 );
  918. lp.seekNonSpace();
  919. if ( lp.isAtTheEnd() ) {
  920. // Empty line
  921. continue;
  922. }
  923. // Parse the line type
  924. var lineType = lp.getToken();
  925. switch ( lineType ) {
  926. // Line type 0: Comment or META
  927. case '0':
  928. // Parse meta directive
  929. var meta = lp.getToken();
  930. if ( meta ) {
  931. switch ( meta ) {
  932. case '!LDRAW_ORG':
  933. type = lp.getToken();
  934. if ( ! parsingEmbeddedFiles ) {
  935. currentParseScope.triangles = [];
  936. currentParseScope.lineSegments = [];
  937. currentParseScope.conditionalSegments = [];
  938. currentParseScope.type = type;
  939. var isRoot = ! parentParseScope.isFromParse;
  940. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  941. currentParseScope.groupObject = new THREE.Group();
  942. }
  943. // If the scale of the object is negated then the triangle winding order
  944. // needs to be flipped.
  945. var matrix = currentParseScope.matrix;
  946. if (
  947. matrix.determinant() < 0 && (
  948. scope.separateObjects && isPrimitiveType( type ) ||
  949. ! scope.separateObjects
  950. ) ) {
  951. currentParseScope.inverted = ! currentParseScope.inverted;
  952. }
  953. triangles = currentParseScope.triangles;
  954. lineSegments = currentParseScope.lineSegments;
  955. conditionalSegments = currentParseScope.conditionalSegments;
  956. }
  957. break;
  958. case '!COLOUR':
  959. var material = this.parseColourMetaDirective( lp );
  960. if ( material ) {
  961. this.addMaterial( material );
  962. } else {
  963. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  964. }
  965. break;
  966. case '!CATEGORY':
  967. category = lp.getToken();
  968. break;
  969. case '!KEYWORDS':
  970. var newKeywords = lp.getRemainingString().split( ',' );
  971. if ( newKeywords.length > 0 ) {
  972. if ( ! keywords ) {
  973. keywords = [];
  974. }
  975. newKeywords.forEach( function ( keyword ) {
  976. keywords.push( keyword.trim() );
  977. } );
  978. }
  979. break;
  980. case 'FILE':
  981. if ( lineIndex > 0 ) {
  982. // Start embedded text files parsing
  983. parsingEmbeddedFiles = true;
  984. currentEmbeddedFileName = lp.getRemainingString();
  985. currentEmbeddedText = '';
  986. bfcCertified = false;
  987. bfcCCW = true;
  988. }
  989. break;
  990. case 'BFC':
  991. // Changes to the backface culling state
  992. while ( ! lp.isAtTheEnd() ) {
  993. var token = lp.getToken();
  994. switch ( token ) {
  995. case 'CERTIFY':
  996. case 'NOCERTIFY':
  997. bfcCertified = token === 'CERTIFY';
  998. bfcCCW = true;
  999. break;
  1000. case 'CW':
  1001. case 'CCW':
  1002. bfcCCW = token === 'CCW';
  1003. break;
  1004. case 'INVERTNEXT':
  1005. bfcInverted = true;
  1006. break;
  1007. case 'CLIP':
  1008. case 'NOCLIP':
  1009. bfcCull = token === 'CLIP';
  1010. break;
  1011. default:
  1012. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  1013. break;
  1014. }
  1015. }
  1016. break;
  1017. default:
  1018. // Other meta directives are not implemented
  1019. break;
  1020. }
  1021. }
  1022. break;
  1023. // Line type 1: Sub-object file
  1024. case '1':
  1025. var material = parseColourCode( lp );
  1026. var posX = parseFloat( lp.getToken() );
  1027. var posY = parseFloat( lp.getToken() );
  1028. var posZ = parseFloat( lp.getToken() );
  1029. var m0 = parseFloat( lp.getToken() );
  1030. var m1 = parseFloat( lp.getToken() );
  1031. var m2 = parseFloat( lp.getToken() );
  1032. var m3 = parseFloat( lp.getToken() );
  1033. var m4 = parseFloat( lp.getToken() );
  1034. var m5 = parseFloat( lp.getToken() );
  1035. var m6 = parseFloat( lp.getToken() );
  1036. var m7 = parseFloat( lp.getToken() );
  1037. var m8 = parseFloat( lp.getToken() );
  1038. var matrix = new THREE.Matrix4().set(
  1039. m0, m1, m2, posX,
  1040. m3, m4, m5, posY,
  1041. m6, m7, m8, posZ,
  1042. 0, 0, 0, 1
  1043. );
  1044. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  1045. if ( scope.fileMap[ fileName ] ) {
  1046. // Found the subobject path in the preloaded file path map
  1047. fileName = scope.fileMap[ fileName ];
  1048. } else {
  1049. // Standardized subfolders
  1050. if ( fileName.startsWith( 's/' ) ) {
  1051. fileName = 'parts/' + fileName;
  1052. } else if ( fileName.startsWith( '48/' ) ) {
  1053. fileName = 'p/' + fileName;
  1054. }
  1055. }
  1056. subobjects.push( {
  1057. material: material,
  1058. matrix: matrix,
  1059. fileName: fileName,
  1060. originalFileName: fileName,
  1061. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  1062. url: null,
  1063. triedLowerCase: false,
  1064. inverted: bfcInverted !== currentParseScope.inverted
  1065. } );
  1066. bfcInverted = false;
  1067. break;
  1068. // Line type 2: Line segment
  1069. case '2':
  1070. var material = parseColourCode( lp, true );
  1071. var segment = {
  1072. material: material.userData.edgeMaterial,
  1073. colourCode: material.userData.code,
  1074. v0: parseVector( lp ),
  1075. v1: parseVector( lp )
  1076. };
  1077. lineSegments.push( segment );
  1078. break;
  1079. // Line type 5: Conditional Line segment
  1080. case '5':
  1081. var material = parseColourCode( lp, true );
  1082. var segment = {
  1083. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  1084. colourCode: material.userData.code,
  1085. v0: parseVector( lp ),
  1086. v1: parseVector( lp ),
  1087. c0: parseVector( lp ),
  1088. c1: parseVector( lp )
  1089. };
  1090. conditionalSegments.push( segment );
  1091. break;
  1092. // Line type 3: Triangle
  1093. case '3':
  1094. var material = parseColourCode( lp );
  1095. var inverted = currentParseScope.inverted;
  1096. var ccw = bfcCCW !== inverted;
  1097. var doubleSided = ! bfcCertified || ! bfcCull;
  1098. var v0, v1, v2, faceNormal;
  1099. if ( ccw === true ) {
  1100. v0 = parseVector( lp );
  1101. v1 = parseVector( lp );
  1102. v2 = parseVector( lp );
  1103. } else {
  1104. v2 = parseVector( lp );
  1105. v1 = parseVector( lp );
  1106. v0 = parseVector( lp );
  1107. }
  1108. tempVec0.subVectors( v1, v0 );
  1109. tempVec1.subVectors( v2, v1 );
  1110. faceNormal = new THREE.Vector3()
  1111. .crossVectors( tempVec0, tempVec1 )
  1112. .normalize();
  1113. triangles.push( {
  1114. material: material,
  1115. colourCode: material.userData.code,
  1116. v0: v0,
  1117. v1: v1,
  1118. v2: v2,
  1119. faceNormal: faceNormal,
  1120. n0: null,
  1121. n1: null,
  1122. n2: null
  1123. } );
  1124. if ( doubleSided === true ) {
  1125. triangles.push( {
  1126. material: material,
  1127. colourCode: material.userData.code,
  1128. v0: v0,
  1129. v1: v2,
  1130. v2: v1,
  1131. faceNormal: faceNormal,
  1132. n0: null,
  1133. n1: null,
  1134. n2: null
  1135. } );
  1136. }
  1137. break;
  1138. // Line type 4: Quadrilateral
  1139. case '4':
  1140. var material = parseColourCode( lp );
  1141. var inverted = currentParseScope.inverted;
  1142. var ccw = bfcCCW !== inverted;
  1143. var doubleSided = ! bfcCertified || ! bfcCull;
  1144. var v0, v1, v2, v3, faceNormal;
  1145. if ( ccw === true ) {
  1146. v0 = parseVector( lp );
  1147. v1 = parseVector( lp );
  1148. v2 = parseVector( lp );
  1149. v3 = parseVector( lp );
  1150. } else {
  1151. v3 = parseVector( lp );
  1152. v2 = parseVector( lp );
  1153. v1 = parseVector( lp );
  1154. v0 = parseVector( lp );
  1155. }
  1156. tempVec0.subVectors( v1, v0 );
  1157. tempVec1.subVectors( v2, v1 );
  1158. faceNormal = new THREE.Vector3()
  1159. .crossVectors( tempVec0, tempVec1 )
  1160. .normalize();
  1161. triangles.push( {
  1162. material: material,
  1163. colourCode: material.userData.code,
  1164. v0: v0,
  1165. v1: v1,
  1166. v2: v2,
  1167. faceNormal: faceNormal,
  1168. n0: null,
  1169. n1: null,
  1170. n2: null
  1171. } );
  1172. triangles.push( {
  1173. material: material,
  1174. colourCode: material.userData.code,
  1175. v0: v0,
  1176. v1: v2,
  1177. v2: v3,
  1178. faceNormal: faceNormal,
  1179. n0: null,
  1180. n1: null,
  1181. n2: null
  1182. } );
  1183. if ( doubleSided === true ) {
  1184. triangles.push( {
  1185. material: material,
  1186. colourCode: material.userData.code,
  1187. v0: v0,
  1188. v1: v2,
  1189. v2: v1,
  1190. faceNormal: faceNormal,
  1191. n0: null,
  1192. n1: null,
  1193. n2: null
  1194. } );
  1195. triangles.push( {
  1196. material: material,
  1197. colourCode: material.userData.code,
  1198. v0: v0,
  1199. v1: v3,
  1200. v2: v2,
  1201. faceNormal: faceNormal,
  1202. n0: null,
  1203. n1: null,
  1204. n2: null
  1205. } );
  1206. }
  1207. break;
  1208. default:
  1209. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1210. break;
  1211. }
  1212. }
  1213. if ( parsingEmbeddedFiles ) {
  1214. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  1215. }
  1216. currentParseScope.category = category;
  1217. currentParseScope.keywords = keywords;
  1218. currentParseScope.subobjects = subobjects;
  1219. currentParseScope.numSubobjects = subobjects.length;
  1220. currentParseScope.subobjectIndex = 0;
  1221. }
  1222. };
  1223. return LDrawLoader;
  1224. } )();