LDrawLoader.js 46 KB

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