LDrawLoader.js 45 KB

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