LDrawLoader.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. FileLoader,
  6. Group,
  7. LineBasicMaterial,
  8. LineSegments,
  9. Loader,
  10. Matrix4,
  11. Mesh,
  12. MeshStandardMaterial,
  13. ShaderMaterial,
  14. SRGBColorSpace,
  15. UniformsLib,
  16. UniformsUtils,
  17. Vector3,
  18. Ray
  19. } from 'three';
  20. // Special surface finish tag types.
  21. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  22. const FINISH_TYPE_DEFAULT = 0;
  23. const FINISH_TYPE_CHROME = 1;
  24. const FINISH_TYPE_PEARLESCENT = 2;
  25. const FINISH_TYPE_RUBBER = 3;
  26. const FINISH_TYPE_MATTE_METALLIC = 4;
  27. const FINISH_TYPE_METAL = 5;
  28. // State machine to search a subobject path.
  29. // The LDraw standard establishes these various possible subfolders.
  30. const FILE_LOCATION_TRY_PARTS = 0;
  31. const FILE_LOCATION_TRY_P = 1;
  32. const FILE_LOCATION_TRY_MODELS = 2;
  33. const FILE_LOCATION_AS_IS = 3;
  34. const FILE_LOCATION_TRY_RELATIVE = 4;
  35. const FILE_LOCATION_TRY_ABSOLUTE = 5;
  36. const FILE_LOCATION_NOT_FOUND = 6;
  37. const MAIN_COLOUR_CODE = '16';
  38. const MAIN_EDGE_COLOUR_CODE = '24';
  39. const COLOR_SPACE_LDRAW = SRGBColorSpace;
  40. const _tempVec0 = new Vector3();
  41. const _tempVec1 = new Vector3();
  42. class LDrawConditionalLineMaterial extends ShaderMaterial {
  43. constructor( parameters ) {
  44. super( {
  45. uniforms: UniformsUtils.merge( [
  46. UniformsLib.fog,
  47. {
  48. diffuse: {
  49. value: new Color()
  50. },
  51. opacity: {
  52. value: 1.0
  53. }
  54. }
  55. ] ),
  56. vertexShader: /* glsl */`
  57. attribute vec3 control0;
  58. attribute vec3 control1;
  59. attribute vec3 direction;
  60. varying float discardFlag;
  61. #include <common>
  62. #include <color_pars_vertex>
  63. #include <fog_pars_vertex>
  64. #include <logdepthbuf_pars_vertex>
  65. #include <clipping_planes_pars_vertex>
  66. void main() {
  67. #include <color_vertex>
  68. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  69. gl_Position = projectionMatrix * mvPosition;
  70. // Transform the line segment ends and control points into camera clip space
  71. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  72. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  73. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  74. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  75. c0.xy /= c0.w;
  76. c1.xy /= c1.w;
  77. p0.xy /= p0.w;
  78. p1.xy /= p1.w;
  79. // Get the direction of the segment and an orthogonal vector
  80. vec2 dir = p1.xy - p0.xy;
  81. vec2 norm = vec2( -dir.y, dir.x );
  82. // Get control point directions from the line
  83. vec2 c0dir = c0.xy - p1.xy;
  84. vec2 c1dir = c1.xy - p1.xy;
  85. // If the vectors to the controls points are pointed in different directions away
  86. // from the line segment then the line should not be drawn.
  87. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  88. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  89. discardFlag = float( sign( d0 ) != sign( d1 ) );
  90. #include <logdepthbuf_vertex>
  91. #include <clipping_planes_vertex>
  92. #include <fog_vertex>
  93. }
  94. `,
  95. fragmentShader: /* glsl */`
  96. uniform vec3 diffuse;
  97. uniform float opacity;
  98. varying float discardFlag;
  99. #include <common>
  100. #include <color_pars_fragment>
  101. #include <fog_pars_fragment>
  102. #include <logdepthbuf_pars_fragment>
  103. #include <clipping_planes_pars_fragment>
  104. void main() {
  105. if ( discardFlag > 0.5 ) discard;
  106. #include <clipping_planes_fragment>
  107. vec3 outgoingLight = vec3( 0.0 );
  108. vec4 diffuseColor = vec4( diffuse, opacity );
  109. #include <logdepthbuf_fragment>
  110. #include <color_fragment>
  111. outgoingLight = diffuseColor.rgb; // simple shader
  112. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  113. #include <tonemapping_fragment>
  114. #include <colorspace_fragment>
  115. #include <fog_fragment>
  116. #include <premultiplied_alpha_fragment>
  117. }
  118. `,
  119. } );
  120. Object.defineProperties( this, {
  121. opacity: {
  122. get: function () {
  123. return this.uniforms.opacity.value;
  124. },
  125. set: function ( value ) {
  126. this.uniforms.opacity.value = value;
  127. }
  128. },
  129. color: {
  130. get: function () {
  131. return this.uniforms.diffuse.value;
  132. }
  133. }
  134. } );
  135. this.setValues( parameters );
  136. this.isLDrawConditionalLineMaterial = true;
  137. }
  138. }
  139. class ConditionalLineSegments extends LineSegments {
  140. constructor( geometry, material ) {
  141. super( geometry, material );
  142. this.isConditionalLine = true;
  143. }
  144. }
  145. function generateFaceNormals( faces ) {
  146. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  147. const face = faces[ i ];
  148. const vertices = face.vertices;
  149. const v0 = vertices[ 0 ];
  150. const v1 = vertices[ 1 ];
  151. const v2 = vertices[ 2 ];
  152. _tempVec0.subVectors( v1, v0 );
  153. _tempVec1.subVectors( v2, v1 );
  154. face.faceNormal = new Vector3()
  155. .crossVectors( _tempVec0, _tempVec1 )
  156. .normalize();
  157. }
  158. }
  159. const _ray = new Ray();
  160. function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
  161. // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
  162. // it allows edges to be smoothed as expected (see minifig arms).
  163. // --
  164. // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
  165. // point errors on vertices along quantization boundaries. Ie after matrix multiplication
  166. // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
  167. // get merged. This added epsilon attempts to push these error values to the same quantized
  168. // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
  169. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  170. function hashVertex( v ) {
  171. const x = ~ ~ ( v.x * hashMultiplier );
  172. const y = ~ ~ ( v.y * hashMultiplier );
  173. const z = ~ ~ ( v.z * hashMultiplier );
  174. return `${ x },${ y },${ z }`;
  175. }
  176. function hashEdge( v0, v1 ) {
  177. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  178. }
  179. // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
  180. // onto the original line.
  181. function toNormalizedRay( v0, v1, targetRay ) {
  182. targetRay.direction.subVectors( v1, v0 ).normalize();
  183. const scalar = v0.dot( targetRay.direction );
  184. targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
  185. return targetRay;
  186. }
  187. function hashRay( ray ) {
  188. return hashEdge( ray.origin, ray.direction );
  189. }
  190. const hardEdges = new Set();
  191. const hardEdgeRays = new Map();
  192. const halfEdgeList = {};
  193. const normals = [];
  194. // Save the list of hard edges by hash
  195. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  196. const ls = lineSegments[ i ];
  197. const vertices = ls.vertices;
  198. const v0 = vertices[ 0 ];
  199. const v1 = vertices[ 1 ];
  200. hardEdges.add( hashEdge( v0, v1 ) );
  201. hardEdges.add( hashEdge( v1, v0 ) );
  202. // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
  203. // and requires more memory.
  204. if ( checkSubSegments ) {
  205. // add both ray directions to the map
  206. const ray = toNormalizedRay( v0, v1, new Ray() );
  207. const rh1 = hashRay( ray );
  208. if ( ! hardEdgeRays.has( rh1 ) ) {
  209. toNormalizedRay( v1, v0, ray );
  210. const rh2 = hashRay( ray );
  211. const info = {
  212. ray,
  213. distances: [],
  214. };
  215. hardEdgeRays.set( rh1, info );
  216. hardEdgeRays.set( rh2, info );
  217. }
  218. // store both segments ends in min, max order in the distances array to check if a face edge is a
  219. // subsegment later.
  220. const info = hardEdgeRays.get( rh1 );
  221. let d0 = info.ray.direction.dot( v0 );
  222. let d1 = info.ray.direction.dot( v1 );
  223. if ( d0 > d1 ) {
  224. [ d0, d1 ] = [ d1, d0 ];
  225. }
  226. info.distances.push( d0, d1 );
  227. }
  228. }
  229. // track the half edges associated with each triangle
  230. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  231. const tri = faces[ i ];
  232. const vertices = tri.vertices;
  233. const vertCount = vertices.length;
  234. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  235. const index = i2;
  236. const next = ( i2 + 1 ) % vertCount;
  237. const v0 = vertices[ index ];
  238. const v1 = vertices[ next ];
  239. const hash = hashEdge( v0, v1 );
  240. // don't add the triangle if the edge is supposed to be hard
  241. if ( hardEdges.has( hash ) ) {
  242. continue;
  243. }
  244. // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
  245. if ( checkSubSegments ) {
  246. toNormalizedRay( v0, v1, _ray );
  247. const rayHash = hashRay( _ray );
  248. if ( hardEdgeRays.has( rayHash ) ) {
  249. const info = hardEdgeRays.get( rayHash );
  250. const { ray, distances } = info;
  251. let d0 = ray.direction.dot( v0 );
  252. let d1 = ray.direction.dot( v1 );
  253. if ( d0 > d1 ) {
  254. [ d0, d1 ] = [ d1, d0 ];
  255. }
  256. // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
  257. let found = false;
  258. for ( let i = 0, l = distances.length; i < l; i += 2 ) {
  259. if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
  260. found = true;
  261. break;
  262. }
  263. }
  264. if ( found ) {
  265. continue;
  266. }
  267. }
  268. }
  269. const info = {
  270. index: index,
  271. tri: tri
  272. };
  273. halfEdgeList[ hash ] = info;
  274. }
  275. }
  276. // Iterate until we've tried to connect all faces to share normals
  277. while ( true ) {
  278. // Stop if there are no more faces left
  279. let halfEdge = null;
  280. for ( const key in halfEdgeList ) {
  281. halfEdge = halfEdgeList[ key ];
  282. break;
  283. }
  284. if ( halfEdge === null ) {
  285. break;
  286. }
  287. // Exhaustively find all connected faces
  288. const queue = [ halfEdge ];
  289. while ( queue.length > 0 ) {
  290. // initialize all vertex normals in this triangle
  291. const tri = queue.pop().tri;
  292. const vertices = tri.vertices;
  293. const vertNormals = tri.normals;
  294. const faceNormal = tri.faceNormal;
  295. // Check if any edge is connected to another triangle edge
  296. const vertCount = vertices.length;
  297. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  298. const index = i2;
  299. const next = ( i2 + 1 ) % vertCount;
  300. const v0 = vertices[ index ];
  301. const v1 = vertices[ next ];
  302. // delete this triangle from the list so it won't be found again
  303. const hash = hashEdge( v0, v1 );
  304. delete halfEdgeList[ hash ];
  305. const reverseHash = hashEdge( v1, v0 );
  306. const otherInfo = halfEdgeList[ reverseHash ];
  307. if ( otherInfo ) {
  308. const otherTri = otherInfo.tri;
  309. const otherIndex = otherInfo.index;
  310. const otherNormals = otherTri.normals;
  311. const otherVertCount = otherNormals.length;
  312. const otherFaceNormal = otherTri.faceNormal;
  313. // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  314. // hard edge. There are some cases where the line segments do not line up exactly
  315. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  316. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  317. continue;
  318. }
  319. // if this triangle has already been traversed then it won't be in
  320. // the halfEdgeList. If it has not then add it to the queue and delete
  321. // it so it won't be found again.
  322. if ( reverseHash in halfEdgeList ) {
  323. queue.push( otherInfo );
  324. delete halfEdgeList[ reverseHash ];
  325. }
  326. // share the first normal
  327. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  328. if (
  329. vertNormals[ index ] && otherNormals[ otherNext ] &&
  330. vertNormals[ index ] !== otherNormals[ otherNext ]
  331. ) {
  332. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  333. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  334. }
  335. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  336. if ( sharedNormal1 === null ) {
  337. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  338. // both edges already have different normals defined and shared. To work around this we create
  339. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  340. sharedNormal1 = { norm: new Vector3() };
  341. normals.push( sharedNormal1.norm );
  342. }
  343. if ( vertNormals[ index ] === null ) {
  344. vertNormals[ index ] = sharedNormal1;
  345. sharedNormal1.norm.add( faceNormal );
  346. }
  347. if ( otherNormals[ otherNext ] === null ) {
  348. otherNormals[ otherNext ] = sharedNormal1;
  349. sharedNormal1.norm.add( otherFaceNormal );
  350. }
  351. // share the second normal
  352. if (
  353. vertNormals[ next ] && otherNormals[ otherIndex ] &&
  354. vertNormals[ next ] !== otherNormals[ otherIndex ]
  355. ) {
  356. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  357. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  358. }
  359. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  360. if ( sharedNormal2 === null ) {
  361. sharedNormal2 = { norm: new Vector3() };
  362. normals.push( sharedNormal2.norm );
  363. }
  364. if ( vertNormals[ next ] === null ) {
  365. vertNormals[ next ] = sharedNormal2;
  366. sharedNormal2.norm.add( faceNormal );
  367. }
  368. if ( otherNormals[ otherIndex ] === null ) {
  369. otherNormals[ otherIndex ] = sharedNormal2;
  370. sharedNormal2.norm.add( otherFaceNormal );
  371. }
  372. }
  373. }
  374. }
  375. }
  376. // The normals of each face have been added up so now we average them by normalizing the vector.
  377. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  378. normals[ i ].normalize();
  379. }
  380. }
  381. function isPartType( type ) {
  382. return type === 'Part' || type === 'Unofficial_Part';
  383. }
  384. function isPrimitiveType( type ) {
  385. return /primitive/i.test( type ) || type === 'Subpart';
  386. }
  387. class LineParser {
  388. constructor( line, lineNumber ) {
  389. this.line = line;
  390. this.lineLength = line.length;
  391. this.currentCharIndex = 0;
  392. this.currentChar = ' ';
  393. this.lineNumber = lineNumber;
  394. }
  395. seekNonSpace() {
  396. while ( this.currentCharIndex < this.lineLength ) {
  397. this.currentChar = this.line.charAt( this.currentCharIndex );
  398. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  399. return;
  400. }
  401. this.currentCharIndex ++;
  402. }
  403. }
  404. getToken() {
  405. const pos0 = this.currentCharIndex ++;
  406. // Seek space
  407. while ( this.currentCharIndex < this.lineLength ) {
  408. this.currentChar = this.line.charAt( this.currentCharIndex );
  409. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  410. break;
  411. }
  412. this.currentCharIndex ++;
  413. }
  414. const pos1 = this.currentCharIndex;
  415. this.seekNonSpace();
  416. return this.line.substring( pos0, pos1 );
  417. }
  418. getVector() {
  419. return new Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
  420. }
  421. getRemainingString() {
  422. return this.line.substring( this.currentCharIndex, this.lineLength );
  423. }
  424. isAtTheEnd() {
  425. return this.currentCharIndex >= this.lineLength;
  426. }
  427. setToEnd() {
  428. this.currentCharIndex = this.lineLength;
  429. }
  430. getLineNumberString() {
  431. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  432. }
  433. }
  434. // Fetches and parses an intermediate representation of LDraw parts files.
  435. class LDrawParsedCache {
  436. constructor( loader ) {
  437. this.loader = loader;
  438. this._cache = {};
  439. }
  440. cloneResult( original ) {
  441. const result = {};
  442. // vertices are transformed and normals computed before being converted to geometry
  443. // so these pieces must be cloned.
  444. result.faces = original.faces.map( face => {
  445. return {
  446. colorCode: face.colorCode,
  447. material: face.material,
  448. vertices: face.vertices.map( v => v.clone() ),
  449. normals: face.normals.map( () => null ),
  450. faceNormal: null
  451. };
  452. } );
  453. result.conditionalSegments = original.conditionalSegments.map( face => {
  454. return {
  455. colorCode: face.colorCode,
  456. material: face.material,
  457. vertices: face.vertices.map( v => v.clone() ),
  458. controlPoints: face.controlPoints.map( v => v.clone() )
  459. };
  460. } );
  461. result.lineSegments = original.lineSegments.map( face => {
  462. return {
  463. colorCode: face.colorCode,
  464. material: face.material,
  465. vertices: face.vertices.map( v => v.clone() )
  466. };
  467. } );
  468. // none if this is subsequently modified
  469. result.type = original.type;
  470. result.category = original.category;
  471. result.keywords = original.keywords;
  472. result.author = original.author;
  473. result.subobjects = original.subobjects;
  474. result.fileName = original.fileName;
  475. result.totalFaces = original.totalFaces;
  476. result.startingBuildingStep = original.startingBuildingStep;
  477. result.materials = original.materials;
  478. result.group = null;
  479. return result;
  480. }
  481. async fetchData( fileName ) {
  482. let triedLowerCase = false;
  483. let locationState = FILE_LOCATION_TRY_PARTS;
  484. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  485. let subobjectURL = fileName;
  486. switch ( locationState ) {
  487. case FILE_LOCATION_AS_IS:
  488. locationState = locationState + 1;
  489. break;
  490. case FILE_LOCATION_TRY_PARTS:
  491. subobjectURL = 'parts/' + subobjectURL;
  492. locationState = locationState + 1;
  493. break;
  494. case FILE_LOCATION_TRY_P:
  495. subobjectURL = 'p/' + subobjectURL;
  496. locationState = locationState + 1;
  497. break;
  498. case FILE_LOCATION_TRY_MODELS:
  499. subobjectURL = 'models/' + subobjectURL;
  500. locationState = locationState + 1;
  501. break;
  502. case FILE_LOCATION_TRY_RELATIVE:
  503. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  504. locationState = locationState + 1;
  505. break;
  506. case FILE_LOCATION_TRY_ABSOLUTE:
  507. if ( triedLowerCase ) {
  508. // Try absolute path
  509. locationState = FILE_LOCATION_NOT_FOUND;
  510. } else {
  511. // Next attempt is lower case
  512. fileName = fileName.toLowerCase();
  513. subobjectURL = fileName;
  514. triedLowerCase = true;
  515. locationState = FILE_LOCATION_TRY_PARTS;
  516. }
  517. break;
  518. }
  519. const loader = this.loader;
  520. const fileLoader = new FileLoader( loader.manager );
  521. fileLoader.setPath( loader.partsLibraryPath );
  522. fileLoader.setRequestHeader( loader.requestHeader );
  523. fileLoader.setWithCredentials( loader.withCredentials );
  524. try {
  525. const text = await fileLoader.loadAsync( subobjectURL );
  526. return text;
  527. } catch ( _ ) {
  528. continue;
  529. }
  530. }
  531. throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
  532. }
  533. parse( text, fileName = null ) {
  534. const loader = this.loader;
  535. // final results
  536. const faces = [];
  537. const lineSegments = [];
  538. const conditionalSegments = [];
  539. const subobjects = [];
  540. const materials = {};
  541. const getLocalMaterial = colorCode => {
  542. return materials[ colorCode ] || null;
  543. };
  544. let type = 'Model';
  545. let category = null;
  546. let keywords = null;
  547. let author = null;
  548. let totalFaces = 0;
  549. // split into lines
  550. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  551. // This is faster than String.split with regex that splits on both
  552. text = text.replace( /\r\n/g, '\n' );
  553. }
  554. const lines = text.split( '\n' );
  555. const numLines = lines.length;
  556. let parsingEmbeddedFiles = false;
  557. let currentEmbeddedFileName = null;
  558. let currentEmbeddedText = null;
  559. let bfcCertified = false;
  560. let bfcCCW = true;
  561. let bfcInverted = false;
  562. let bfcCull = true;
  563. let startingBuildingStep = false;
  564. // Parse all line commands
  565. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  566. const line = lines[ lineIndex ];
  567. if ( line.length === 0 ) continue;
  568. if ( parsingEmbeddedFiles ) {
  569. if ( line.startsWith( '0 FILE ' ) ) {
  570. // Save previous embedded file in the cache
  571. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  572. // New embedded text file
  573. currentEmbeddedFileName = line.substring( 7 );
  574. currentEmbeddedText = '';
  575. } else {
  576. currentEmbeddedText += line + '\n';
  577. }
  578. continue;
  579. }
  580. const lp = new LineParser( line, lineIndex + 1 );
  581. lp.seekNonSpace();
  582. if ( lp.isAtTheEnd() ) {
  583. // Empty line
  584. continue;
  585. }
  586. // Parse the line type
  587. const lineType = lp.getToken();
  588. let material;
  589. let colorCode;
  590. let segment;
  591. let ccw;
  592. let doubleSided;
  593. let v0, v1, v2, v3, c0, c1;
  594. switch ( lineType ) {
  595. // Line type 0: Comment or META
  596. case '0':
  597. // Parse meta directive
  598. const meta = lp.getToken();
  599. if ( meta ) {
  600. switch ( meta ) {
  601. case '!LDRAW_ORG':
  602. type = lp.getToken();
  603. break;
  604. case '!COLOUR':
  605. material = loader.parseColorMetaDirective( lp );
  606. if ( material ) {
  607. materials[ material.userData.code ] = material;
  608. } else {
  609. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  610. }
  611. break;
  612. case '!CATEGORY':
  613. category = lp.getToken();
  614. break;
  615. case '!KEYWORDS':
  616. const newKeywords = lp.getRemainingString().split( ',' );
  617. if ( newKeywords.length > 0 ) {
  618. if ( ! keywords ) {
  619. keywords = [];
  620. }
  621. newKeywords.forEach( function ( keyword ) {
  622. keywords.push( keyword.trim() );
  623. } );
  624. }
  625. break;
  626. case 'FILE':
  627. if ( lineIndex > 0 ) {
  628. // Start embedded text files parsing
  629. parsingEmbeddedFiles = true;
  630. currentEmbeddedFileName = lp.getRemainingString();
  631. currentEmbeddedText = '';
  632. bfcCertified = false;
  633. bfcCCW = true;
  634. }
  635. break;
  636. case 'BFC':
  637. // Changes to the backface culling state
  638. while ( ! lp.isAtTheEnd() ) {
  639. const token = lp.getToken();
  640. switch ( token ) {
  641. case 'CERTIFY':
  642. case 'NOCERTIFY':
  643. bfcCertified = token === 'CERTIFY';
  644. bfcCCW = true;
  645. break;
  646. case 'CW':
  647. case 'CCW':
  648. bfcCCW = token === 'CCW';
  649. break;
  650. case 'INVERTNEXT':
  651. bfcInverted = true;
  652. break;
  653. case 'CLIP':
  654. case 'NOCLIP':
  655. bfcCull = token === 'CLIP';
  656. break;
  657. default:
  658. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  659. break;
  660. }
  661. }
  662. break;
  663. case 'STEP':
  664. startingBuildingStep = true;
  665. break;
  666. case 'Author:':
  667. author = lp.getToken();
  668. break;
  669. default:
  670. // Other meta directives are not implemented
  671. break;
  672. }
  673. }
  674. break;
  675. // Line type 1: Sub-object file
  676. case '1':
  677. colorCode = lp.getToken();
  678. material = getLocalMaterial( colorCode );
  679. const posX = parseFloat( lp.getToken() );
  680. const posY = parseFloat( lp.getToken() );
  681. const posZ = parseFloat( lp.getToken() );
  682. const m0 = parseFloat( lp.getToken() );
  683. const m1 = parseFloat( lp.getToken() );
  684. const m2 = parseFloat( lp.getToken() );
  685. const m3 = parseFloat( lp.getToken() );
  686. const m4 = parseFloat( lp.getToken() );
  687. const m5 = parseFloat( lp.getToken() );
  688. const m6 = parseFloat( lp.getToken() );
  689. const m7 = parseFloat( lp.getToken() );
  690. const m8 = parseFloat( lp.getToken() );
  691. const matrix = new Matrix4().set(
  692. m0, m1, m2, posX,
  693. m3, m4, m5, posY,
  694. m6, m7, m8, posZ,
  695. 0, 0, 0, 1
  696. );
  697. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  698. if ( loader.fileMap[ fileName ] ) {
  699. // Found the subobject path in the preloaded file path map
  700. fileName = loader.fileMap[ fileName ];
  701. } else {
  702. // Standardized subfolders
  703. if ( fileName.startsWith( 's/' ) ) {
  704. fileName = 'parts/' + fileName;
  705. } else if ( fileName.startsWith( '48/' ) ) {
  706. fileName = 'p/' + fileName;
  707. }
  708. }
  709. subobjects.push( {
  710. material: material,
  711. colorCode: colorCode,
  712. matrix: matrix,
  713. fileName: fileName,
  714. inverted: bfcInverted,
  715. startingBuildingStep: startingBuildingStep
  716. } );
  717. startingBuildingStep = false;
  718. bfcInverted = false;
  719. break;
  720. // Line type 2: Line segment
  721. case '2':
  722. colorCode = lp.getToken();
  723. material = getLocalMaterial( colorCode );
  724. v0 = lp.getVector();
  725. v1 = lp.getVector();
  726. segment = {
  727. material: material,
  728. colorCode: colorCode,
  729. vertices: [ v0, v1 ],
  730. };
  731. lineSegments.push( segment );
  732. break;
  733. // Line type 5: Conditional Line segment
  734. case '5':
  735. colorCode = lp.getToken();
  736. material = getLocalMaterial( colorCode );
  737. v0 = lp.getVector();
  738. v1 = lp.getVector();
  739. c0 = lp.getVector();
  740. c1 = lp.getVector();
  741. segment = {
  742. material: material,
  743. colorCode: colorCode,
  744. vertices: [ v0, v1 ],
  745. controlPoints: [ c0, c1 ],
  746. };
  747. conditionalSegments.push( segment );
  748. break;
  749. // Line type 3: Triangle
  750. case '3':
  751. colorCode = lp.getToken();
  752. material = getLocalMaterial( colorCode );
  753. ccw = bfcCCW;
  754. doubleSided = ! bfcCertified || ! bfcCull;
  755. if ( ccw === true ) {
  756. v0 = lp.getVector();
  757. v1 = lp.getVector();
  758. v2 = lp.getVector();
  759. } else {
  760. v2 = lp.getVector();
  761. v1 = lp.getVector();
  762. v0 = lp.getVector();
  763. }
  764. faces.push( {
  765. material: material,
  766. colorCode: colorCode,
  767. faceNormal: null,
  768. vertices: [ v0, v1, v2 ],
  769. normals: [ null, null, null ],
  770. } );
  771. totalFaces ++;
  772. if ( doubleSided === true ) {
  773. faces.push( {
  774. material: material,
  775. colorCode: colorCode,
  776. faceNormal: null,
  777. vertices: [ v2, v1, v0 ],
  778. normals: [ null, null, null ],
  779. } );
  780. totalFaces ++;
  781. }
  782. break;
  783. // Line type 4: Quadrilateral
  784. case '4':
  785. colorCode = lp.getToken();
  786. material = getLocalMaterial( colorCode );
  787. ccw = bfcCCW;
  788. doubleSided = ! bfcCertified || ! bfcCull;
  789. if ( ccw === true ) {
  790. v0 = lp.getVector();
  791. v1 = lp.getVector();
  792. v2 = lp.getVector();
  793. v3 = lp.getVector();
  794. } else {
  795. v3 = lp.getVector();
  796. v2 = lp.getVector();
  797. v1 = lp.getVector();
  798. v0 = lp.getVector();
  799. }
  800. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  801. // account for the doubling of vertices later when smoothing normals.
  802. faces.push( {
  803. material: material,
  804. colorCode: colorCode,
  805. faceNormal: null,
  806. vertices: [ v0, v1, v2, v3 ],
  807. normals: [ null, null, null, null ],
  808. } );
  809. totalFaces += 2;
  810. if ( doubleSided === true ) {
  811. faces.push( {
  812. material: material,
  813. colorCode: colorCode,
  814. faceNormal: null,
  815. vertices: [ v3, v2, v1, v0 ],
  816. normals: [ null, null, null, null ],
  817. } );
  818. totalFaces += 2;
  819. }
  820. break;
  821. default:
  822. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  823. }
  824. }
  825. if ( parsingEmbeddedFiles ) {
  826. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  827. }
  828. return {
  829. faces,
  830. conditionalSegments,
  831. lineSegments,
  832. type,
  833. category,
  834. keywords,
  835. author,
  836. subobjects,
  837. totalFaces,
  838. startingBuildingStep,
  839. materials,
  840. fileName,
  841. group: null
  842. };
  843. }
  844. // returns an (optionally cloned) instance of the data
  845. getData( fileName, clone = true ) {
  846. const key = fileName.toLowerCase();
  847. const result = this._cache[ key ];
  848. if ( result === null || result instanceof Promise ) {
  849. return null;
  850. }
  851. if ( clone ) {
  852. return this.cloneResult( result );
  853. } else {
  854. return result;
  855. }
  856. }
  857. // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  858. // the data is ready to use and can be retrieved synchronously with "getData".
  859. async ensureDataLoaded( fileName ) {
  860. const key = fileName.toLowerCase();
  861. if ( ! ( key in this._cache ) ) {
  862. // replace the promise with a copy of the parsed data for immediate processing
  863. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  864. const info = this.parse( text, fileName );
  865. this._cache[ key ] = info;
  866. return info;
  867. } );
  868. }
  869. await this._cache[ key ];
  870. }
  871. // sets the data in the cache from parsed data
  872. setData( fileName, text ) {
  873. const key = fileName.toLowerCase();
  874. this._cache[ key ] = this.parse( text, fileName );
  875. }
  876. }
  877. // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  878. // an edge then the passthroughColorCode is used.
  879. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  880. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  881. if ( isPassthrough ) {
  882. colorCode = parentColorCode;
  883. }
  884. return materialHierarchy[ colorCode ] || null;
  885. }
  886. // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  887. class LDrawPartsGeometryCache {
  888. constructor( loader ) {
  889. this.loader = loader;
  890. this.parseCache = new LDrawParsedCache( loader );
  891. this._cache = {};
  892. }
  893. // Convert the given file information into a mesh by processing subobjects.
  894. async processIntoMesh( info ) {
  895. const loader = this.loader;
  896. const parseCache = this.parseCache;
  897. const faceMaterials = new Set();
  898. // Processes the part subobject information to load child parts and merge geometry onto part
  899. // piece object.
  900. const processInfoSubobjects = async ( info, subobject = null ) => {
  901. const subobjects = info.subobjects;
  902. const promises = [];
  903. // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  904. // group which lets instruction steps apply correctly.
  905. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  906. const subobject = subobjects[ i ];
  907. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  908. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  909. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  910. return this.loadModel( subobject.fileName ).catch( error => {
  911. console.warn( error );
  912. return null;
  913. } );
  914. }
  915. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  916. } );
  917. promises.push( promise );
  918. }
  919. const group = new Group();
  920. group.userData.category = info.category;
  921. group.userData.keywords = info.keywords;
  922. group.userData.author = info.author;
  923. group.userData.type = info.type;
  924. group.userData.fileName = info.fileName;
  925. info.group = group;
  926. const subobjectInfos = await Promise.all( promises );
  927. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  928. const subobject = info.subobjects[ i ];
  929. const subobjectInfo = subobjectInfos[ i ];
  930. if ( subobjectInfo === null ) {
  931. // the subobject failed to load
  932. continue;
  933. }
  934. // if the subobject was loaded as a separate group then apply the parent scopes materials
  935. if ( subobjectInfo.isGroup ) {
  936. const subobjectGroup = subobjectInfo;
  937. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  938. subobjectGroup.userData.startingBuildingStep = subobject.startingBuildingStep;
  939. subobjectGroup.name = subobject.fileName;
  940. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  941. subobjectGroup.userData.colorCode = subobject.colorCode;
  942. group.add( subobjectGroup );
  943. continue;
  944. }
  945. // add the subobject group if it has children in case it has both children and primitives
  946. if ( subobjectInfo.group.children.length ) {
  947. group.add( subobjectInfo.group );
  948. }
  949. // transform the primitives into the local space of the parent piece and append them to
  950. // to the parent primitives list.
  951. const parentLineSegments = info.lineSegments;
  952. const parentConditionalSegments = info.conditionalSegments;
  953. const parentFaces = info.faces;
  954. const lineSegments = subobjectInfo.lineSegments;
  955. const conditionalSegments = subobjectInfo.conditionalSegments;
  956. const faces = subobjectInfo.faces;
  957. const matrix = subobject.matrix;
  958. const inverted = subobject.inverted;
  959. const matrixScaleInverted = matrix.determinant() < 0;
  960. const colorCode = subobject.colorCode;
  961. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  962. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  963. const ls = lineSegments[ i ];
  964. const vertices = ls.vertices;
  965. vertices[ 0 ].applyMatrix4( matrix );
  966. vertices[ 1 ].applyMatrix4( matrix );
  967. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  968. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  969. parentLineSegments.push( ls );
  970. }
  971. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  972. const os = conditionalSegments[ i ];
  973. const vertices = os.vertices;
  974. const controlPoints = os.controlPoints;
  975. vertices[ 0 ].applyMatrix4( matrix );
  976. vertices[ 1 ].applyMatrix4( matrix );
  977. controlPoints[ 0 ].applyMatrix4( matrix );
  978. controlPoints[ 1 ].applyMatrix4( matrix );
  979. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  980. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  981. parentConditionalSegments.push( os );
  982. }
  983. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  984. const tri = faces[ i ];
  985. const vertices = tri.vertices;
  986. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  987. vertices[ i ].applyMatrix4( matrix );
  988. }
  989. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  990. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  991. faceMaterials.add( tri.colorCode );
  992. // If the scale of the object is negated then the triangle winding order
  993. // needs to be flipped.
  994. if ( matrixScaleInverted !== inverted ) {
  995. vertices.reverse();
  996. }
  997. parentFaces.push( tri );
  998. }
  999. info.totalFaces += subobjectInfo.totalFaces;
  1000. }
  1001. // Apply the parent subobjects pass through material code to this object. This is done several times due
  1002. // to material scoping.
  1003. if ( subobject ) {
  1004. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  1005. group.userData.colorCode = subobject.colorCode;
  1006. }
  1007. return info;
  1008. };
  1009. // Track material use to see if we need to use the normal smooth slow path for hard edges.
  1010. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  1011. faceMaterials.add( info.faces[ i ].colorCode );
  1012. }
  1013. await processInfoSubobjects( info );
  1014. if ( loader.smoothNormals ) {
  1015. const checkSubSegments = faceMaterials.size > 1;
  1016. generateFaceNormals( info.faces );
  1017. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  1018. }
  1019. // Add the primitive objects and metadata.
  1020. const group = info.group;
  1021. if ( info.faces.length > 0 ) {
  1022. group.add( createObject( this.loader, info.faces, 3, false, info.totalFaces ) );
  1023. }
  1024. if ( info.lineSegments.length > 0 ) {
  1025. group.add( createObject( this.loader, info.lineSegments, 2 ) );
  1026. }
  1027. if ( info.conditionalSegments.length > 0 ) {
  1028. group.add( createObject( this.loader, info.conditionalSegments, 2, true ) );
  1029. }
  1030. return group;
  1031. }
  1032. hasCachedModel( fileName ) {
  1033. return fileName !== null && fileName.toLowerCase() in this._cache;
  1034. }
  1035. async getCachedModel( fileName ) {
  1036. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  1037. const key = fileName.toLowerCase();
  1038. const group = await this._cache[ key ];
  1039. return group.clone();
  1040. } else {
  1041. return null;
  1042. }
  1043. }
  1044. // Loads and parses the model with the given file name. Returns a cached copy if available.
  1045. async loadModel( fileName ) {
  1046. const parseCache = this.parseCache;
  1047. const key = fileName.toLowerCase();
  1048. if ( this.hasCachedModel( fileName ) ) {
  1049. // Return cached model if available.
  1050. return this.getCachedModel( fileName );
  1051. } else {
  1052. // Otherwise parse a new model.
  1053. // Ensure the file data is loaded and pre parsed.
  1054. await parseCache.ensureDataLoaded( fileName );
  1055. const info = parseCache.getData( fileName );
  1056. const promise = this.processIntoMesh( info );
  1057. // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  1058. // so check the cache again to see if it's been added since the last async operation so we don't
  1059. // do unnecessary work.
  1060. if ( this.hasCachedModel( fileName ) ) {
  1061. return this.getCachedModel( fileName );
  1062. }
  1063. // Cache object if it's a part so it can be reused later.
  1064. if ( isPartType( info.type ) ) {
  1065. this._cache[ key ] = promise;
  1066. }
  1067. // return a copy
  1068. const group = await promise;
  1069. return group.clone();
  1070. }
  1071. }
  1072. // parses the given model text into a renderable object. Returns cached copy if available.
  1073. async parseModel( text ) {
  1074. const parseCache = this.parseCache;
  1075. const info = parseCache.parse( text );
  1076. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  1077. return this.getCachedModel( info.fileName );
  1078. }
  1079. return this.processIntoMesh( info );
  1080. }
  1081. }
  1082. function sortByMaterial( a, b ) {
  1083. if ( a.colorCode === b.colorCode ) {
  1084. return 0;
  1085. }
  1086. if ( a.colorCode < b.colorCode ) {
  1087. return - 1;
  1088. }
  1089. return 1;
  1090. }
  1091. function createObject( loader, elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  1092. // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
  1093. // With per face / segment material, implemented with mesh groups and materials array
  1094. // Sort the faces or line segments by color code to make later the mesh groups
  1095. elements.sort( sortByMaterial );
  1096. if ( totalElements === null ) {
  1097. totalElements = elements.length;
  1098. }
  1099. const positions = new Float32Array( elementSize * totalElements * 3 );
  1100. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1101. const materials = [];
  1102. const quadArray = new Array( 6 );
  1103. const bufferGeometry = new BufferGeometry();
  1104. let prevMaterial = null;
  1105. let index0 = 0;
  1106. let numGroupVerts = 0;
  1107. let offset = 0;
  1108. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1109. const elem = elements[ iElem ];
  1110. let vertices = elem.vertices;
  1111. if ( vertices.length === 4 ) {
  1112. quadArray[ 0 ] = vertices[ 0 ];
  1113. quadArray[ 1 ] = vertices[ 1 ];
  1114. quadArray[ 2 ] = vertices[ 2 ];
  1115. quadArray[ 3 ] = vertices[ 0 ];
  1116. quadArray[ 4 ] = vertices[ 2 ];
  1117. quadArray[ 5 ] = vertices[ 3 ];
  1118. vertices = quadArray;
  1119. }
  1120. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1121. const v = vertices[ j ];
  1122. const index = offset + j * 3;
  1123. positions[ index + 0 ] = v.x;
  1124. positions[ index + 1 ] = v.y;
  1125. positions[ index + 2 ] = v.z;
  1126. }
  1127. // create the normals array if this is a set of faces
  1128. if ( elementSize === 3 ) {
  1129. if ( ! elem.faceNormal ) {
  1130. const v0 = vertices[ 0 ];
  1131. const v1 = vertices[ 1 ];
  1132. const v2 = vertices[ 2 ];
  1133. _tempVec0.subVectors( v1, v0 );
  1134. _tempVec1.subVectors( v2, v1 );
  1135. elem.faceNormal = new Vector3()
  1136. .crossVectors( _tempVec0, _tempVec1 )
  1137. .normalize();
  1138. }
  1139. let elemNormals = elem.normals;
  1140. if ( elemNormals.length === 4 ) {
  1141. quadArray[ 0 ] = elemNormals[ 0 ];
  1142. quadArray[ 1 ] = elemNormals[ 1 ];
  1143. quadArray[ 2 ] = elemNormals[ 2 ];
  1144. quadArray[ 3 ] = elemNormals[ 0 ];
  1145. quadArray[ 4 ] = elemNormals[ 2 ];
  1146. quadArray[ 5 ] = elemNormals[ 3 ];
  1147. elemNormals = quadArray;
  1148. }
  1149. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1150. // use face normal if a vertex normal is not provided
  1151. let n = elem.faceNormal;
  1152. if ( elemNormals[ j ] ) {
  1153. n = elemNormals[ j ].norm;
  1154. }
  1155. const index = offset + j * 3;
  1156. normals[ index + 0 ] = n.x;
  1157. normals[ index + 1 ] = n.y;
  1158. normals[ index + 2 ] = n.z;
  1159. }
  1160. }
  1161. if ( prevMaterial !== elem.colorCode ) {
  1162. if ( prevMaterial !== null ) {
  1163. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1164. }
  1165. const material = elem.material;
  1166. if ( material !== null ) {
  1167. if ( elementSize === 3 ) {
  1168. materials.push( material );
  1169. } else if ( elementSize === 2 ) {
  1170. if ( isConditionalSegments ) {
  1171. const edgeMaterial = loader.edgeMaterialCache.get( material );
  1172. materials.push( loader.conditionalEdgeMaterialCache.get( edgeMaterial ) );
  1173. } else {
  1174. materials.push( loader.edgeMaterialCache.get( material ) );
  1175. }
  1176. }
  1177. } else {
  1178. // If a material has not been made available yet then keep the color code string in the material array
  1179. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1180. materials.push( elem.colorCode );
  1181. }
  1182. prevMaterial = elem.colorCode;
  1183. index0 = offset / 3;
  1184. numGroupVerts = vertices.length;
  1185. } else {
  1186. numGroupVerts += vertices.length;
  1187. }
  1188. offset += 3 * vertices.length;
  1189. }
  1190. if ( numGroupVerts > 0 ) {
  1191. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1192. }
  1193. bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1194. if ( normals !== null ) {
  1195. bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  1196. }
  1197. let object3d = null;
  1198. if ( elementSize === 2 ) {
  1199. if ( isConditionalSegments ) {
  1200. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1201. } else {
  1202. object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1203. }
  1204. } else if ( elementSize === 3 ) {
  1205. object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1206. }
  1207. if ( isConditionalSegments ) {
  1208. object3d.isConditionalLine = true;
  1209. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1210. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1211. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1212. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1213. const os = elements[ i ];
  1214. const vertices = os.vertices;
  1215. const controlPoints = os.controlPoints;
  1216. const c0 = controlPoints[ 0 ];
  1217. const c1 = controlPoints[ 1 ];
  1218. const v0 = vertices[ 0 ];
  1219. const v1 = vertices[ 1 ];
  1220. const index = i * 3 * 2;
  1221. controlArray0[ index + 0 ] = c0.x;
  1222. controlArray0[ index + 1 ] = c0.y;
  1223. controlArray0[ index + 2 ] = c0.z;
  1224. controlArray0[ index + 3 ] = c0.x;
  1225. controlArray0[ index + 4 ] = c0.y;
  1226. controlArray0[ index + 5 ] = c0.z;
  1227. controlArray1[ index + 0 ] = c1.x;
  1228. controlArray1[ index + 1 ] = c1.y;
  1229. controlArray1[ index + 2 ] = c1.z;
  1230. controlArray1[ index + 3 ] = c1.x;
  1231. controlArray1[ index + 4 ] = c1.y;
  1232. controlArray1[ index + 5 ] = c1.z;
  1233. directionArray[ index + 0 ] = v1.x - v0.x;
  1234. directionArray[ index + 1 ] = v1.y - v0.y;
  1235. directionArray[ index + 2 ] = v1.z - v0.z;
  1236. directionArray[ index + 3 ] = v1.x - v0.x;
  1237. directionArray[ index + 4 ] = v1.y - v0.y;
  1238. directionArray[ index + 5 ] = v1.z - v0.z;
  1239. }
  1240. bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
  1241. bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
  1242. bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
  1243. }
  1244. return object3d;
  1245. }
  1246. //
  1247. class LDrawLoader extends Loader {
  1248. constructor( manager ) {
  1249. super( manager );
  1250. // Array of THREE.Material
  1251. this.materials = [];
  1252. this.materialLibrary = {};
  1253. this.edgeMaterialCache = new WeakMap();
  1254. this.conditionalEdgeMaterialCache = new WeakMap();
  1255. // This also allows to handle the embedded text files ("0 FILE" lines)
  1256. this.partsCache = new LDrawPartsGeometryCache( this );
  1257. // 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.
  1258. this.fileMap = {};
  1259. // Initializes the materials library with default materials
  1260. this.setMaterials( [] );
  1261. // If this flag is set to true the vertex normals will be smoothed.
  1262. this.smoothNormals = true;
  1263. // The path to load parts from the LDraw parts library from.
  1264. this.partsLibraryPath = '';
  1265. // Material assigned to not available colors for meshes and edges
  1266. this.missingColorMaterial = new MeshStandardMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF, roughness: 0.3, metalness: 0 } );
  1267. this.missingEdgeColorMaterial = new LineBasicMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF } );
  1268. this.missingConditionalEdgeColorMaterial = new LDrawConditionalLineMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, fog: true, color: 0xFF00FF } );
  1269. this.edgeMaterialCache.set( this.missingColorMaterial, this.missingEdgeColorMaterial );
  1270. this.conditionalEdgeMaterialCache.set( this.missingEdgeColorMaterial, this.missingConditionalEdgeColorMaterial );
  1271. }
  1272. setPartsLibraryPath( path ) {
  1273. this.partsLibraryPath = path;
  1274. return this;
  1275. }
  1276. async preloadMaterials( url ) {
  1277. const fileLoader = new FileLoader( this.manager );
  1278. fileLoader.setPath( this.path );
  1279. fileLoader.setRequestHeader( this.requestHeader );
  1280. fileLoader.setWithCredentials( this.withCredentials );
  1281. const text = await fileLoader.loadAsync( url );
  1282. const colorLineRegex = /^0 !COLOUR/;
  1283. const lines = text.split( /[\n\r]/g );
  1284. const materials = [];
  1285. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1286. const line = lines[ i ];
  1287. if ( colorLineRegex.test( line ) ) {
  1288. const directive = line.replace( colorLineRegex, '' );
  1289. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1290. materials.push( material );
  1291. }
  1292. }
  1293. this.setMaterials( materials );
  1294. }
  1295. load( url, onLoad, onProgress, onError ) {
  1296. const fileLoader = new FileLoader( this.manager );
  1297. fileLoader.setPath( this.path );
  1298. fileLoader.setRequestHeader( this.requestHeader );
  1299. fileLoader.setWithCredentials( this.withCredentials );
  1300. fileLoader.load( url, text => {
  1301. this.partsCache
  1302. .parseModel( text, this.materialLibrary )
  1303. .then( group => {
  1304. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1305. this.computeBuildingSteps( group );
  1306. group.userData.fileName = url;
  1307. onLoad( group );
  1308. } )
  1309. .catch( onError );
  1310. }, onProgress, onError );
  1311. }
  1312. parse( text, onLoad, onError ) {
  1313. this.partsCache
  1314. .parseModel( text, this.materialLibrary )
  1315. .then( group => {
  1316. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1317. this.computeBuildingSteps( group );
  1318. group.userData.fileName = '';
  1319. onLoad( group );
  1320. } )
  1321. .catch( onError );
  1322. }
  1323. setMaterials( materials ) {
  1324. this.materialLibrary = {};
  1325. this.materials = [];
  1326. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1327. this.addMaterial( materials[ i ] );
  1328. }
  1329. // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1330. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1331. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1332. return this;
  1333. }
  1334. setFileMap( fileMap ) {
  1335. this.fileMap = fileMap;
  1336. return this;
  1337. }
  1338. addMaterial( material ) {
  1339. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1340. const matLib = this.materialLibrary;
  1341. if ( ! matLib[ material.userData.code ] ) {
  1342. this.materials.push( material );
  1343. matLib[ material.userData.code ] = material;
  1344. }
  1345. return this;
  1346. }
  1347. getMaterial( colorCode ) {
  1348. if ( colorCode.startsWith( '0x2' ) ) {
  1349. // Special 'direct' material value (RGB color)
  1350. const color = colorCode.substring( 3 );
  1351. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1352. }
  1353. return this.materialLibrary[ colorCode ] || null;
  1354. }
  1355. // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1356. // in the material array if they need to be filled in.
  1357. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1358. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1359. const loader = this;
  1360. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1361. group.traverse( c => {
  1362. if ( c.isMesh || c.isLineSegments ) {
  1363. if ( Array.isArray( c.material ) ) {
  1364. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1365. if ( ! c.material[ i ].isMaterial ) {
  1366. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1367. }
  1368. }
  1369. } else if ( ! c.material.isMaterial ) {
  1370. c.material = getMaterial( c, c.material );
  1371. }
  1372. }
  1373. } );
  1374. // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1375. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1376. // simply returned for the subsequent material application.
  1377. function getMaterial( c, colorCode ) {
  1378. // if our parent is a passthrough color code and we don't have the current material color available then
  1379. // return early.
  1380. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1381. return colorCode;
  1382. }
  1383. const forEdge = c.isLineSegments || c.isConditionalLine;
  1384. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1385. if ( isPassthrough ) {
  1386. colorCode = parentColorCode;
  1387. }
  1388. let material = null;
  1389. if ( colorCode in materialHierarchy ) {
  1390. material = materialHierarchy[ colorCode ];
  1391. } else if ( finalMaterialPass ) {
  1392. // see if we can get the final material from from the "getMaterial" function which will attempt to
  1393. // parse the "direct" colors
  1394. material = loader.getMaterial( colorCode );
  1395. if ( material === null ) {
  1396. // otherwise throw a warning if this is final opportunity to set the material
  1397. console.warn( `LDrawLoader: Material properties for code ${ colorCode } not available.` );
  1398. // And return the 'missing color' material
  1399. material = loader.missingColorMaterial;
  1400. }
  1401. } else {
  1402. return colorCode;
  1403. }
  1404. if ( c.isLineSegments ) {
  1405. material = loader.edgeMaterialCache.get( material );
  1406. if ( c.isConditionalLine ) {
  1407. material = loader.conditionalEdgeMaterialCache.get( material );
  1408. }
  1409. }
  1410. return material;
  1411. }
  1412. }
  1413. getMainMaterial() {
  1414. return this.getMaterial( MAIN_COLOUR_CODE );
  1415. }
  1416. getMainEdgeMaterial() {
  1417. const mat = this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1418. return mat ? this.edgeMaterialCache.get( mat ) : null;
  1419. }
  1420. parseColorMetaDirective( lineParser ) {
  1421. // Parses a color definition and returns a THREE.Material
  1422. let code = null;
  1423. // Triangle and line colors
  1424. let fillColor = '#FF00FF';
  1425. let edgeColor = '#FF00FF';
  1426. // Transparency
  1427. let alpha = 1;
  1428. let isTransparent = false;
  1429. // Self-illumination:
  1430. let luminance = 0;
  1431. let finishType = FINISH_TYPE_DEFAULT;
  1432. let edgeMaterial = null;
  1433. const name = lineParser.getToken();
  1434. if ( ! name ) {
  1435. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  1436. }
  1437. // Parse tag tokens and their parameters
  1438. let token = null;
  1439. while ( true ) {
  1440. token = lineParser.getToken();
  1441. if ( ! token ) {
  1442. break;
  1443. }
  1444. if ( ! parseLuminance( token ) ) {
  1445. switch ( token.toUpperCase() ) {
  1446. case 'CODE':
  1447. code = lineParser.getToken();
  1448. break;
  1449. case 'VALUE':
  1450. fillColor = lineParser.getToken();
  1451. if ( fillColor.startsWith( '0x' ) ) {
  1452. fillColor = '#' + fillColor.substring( 2 );
  1453. } else if ( ! fillColor.startsWith( '#' ) ) {
  1454. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1455. }
  1456. break;
  1457. case 'EDGE':
  1458. edgeColor = lineParser.getToken();
  1459. if ( edgeColor.startsWith( '0x' ) ) {
  1460. edgeColor = '#' + edgeColor.substring( 2 );
  1461. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1462. // Try to see if edge color is a color code
  1463. edgeMaterial = this.getMaterial( edgeColor );
  1464. if ( ! edgeMaterial ) {
  1465. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1466. }
  1467. // Get the edge material for this triangle material
  1468. edgeMaterial = this.edgeMaterialCache.get( edgeMaterial );
  1469. }
  1470. break;
  1471. case 'ALPHA':
  1472. alpha = parseInt( lineParser.getToken() );
  1473. if ( isNaN( alpha ) ) {
  1474. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1475. }
  1476. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1477. if ( alpha < 1 ) {
  1478. isTransparent = true;
  1479. }
  1480. break;
  1481. case 'LUMINANCE':
  1482. if ( ! parseLuminance( lineParser.getToken() ) ) {
  1483. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  1484. }
  1485. break;
  1486. case 'CHROME':
  1487. finishType = FINISH_TYPE_CHROME;
  1488. break;
  1489. case 'PEARLESCENT':
  1490. finishType = FINISH_TYPE_PEARLESCENT;
  1491. break;
  1492. case 'RUBBER':
  1493. finishType = FINISH_TYPE_RUBBER;
  1494. break;
  1495. case 'MATTE_METALLIC':
  1496. finishType = FINISH_TYPE_MATTE_METALLIC;
  1497. break;
  1498. case 'METAL':
  1499. finishType = FINISH_TYPE_METAL;
  1500. break;
  1501. case 'MATERIAL':
  1502. // Not implemented
  1503. lineParser.setToEnd();
  1504. break;
  1505. default:
  1506. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1507. }
  1508. }
  1509. }
  1510. let material = null;
  1511. switch ( finishType ) {
  1512. case FINISH_TYPE_DEFAULT:
  1513. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0 } );
  1514. break;
  1515. case FINISH_TYPE_PEARLESCENT:
  1516. // Try to imitate pearlescency by making the surface glossy
  1517. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0.25 } );
  1518. break;
  1519. case FINISH_TYPE_CHROME:
  1520. // Mirror finish surface
  1521. material = new MeshStandardMaterial( { roughness: 0, metalness: 1 } );
  1522. break;
  1523. case FINISH_TYPE_RUBBER:
  1524. // Rubber finish
  1525. material = new MeshStandardMaterial( { roughness: 0.9, metalness: 0 } );
  1526. break;
  1527. case FINISH_TYPE_MATTE_METALLIC:
  1528. // Brushed metal finish
  1529. material = new MeshStandardMaterial( { roughness: 0.8, metalness: 0.4 } );
  1530. break;
  1531. case FINISH_TYPE_METAL:
  1532. // Average metal finish
  1533. material = new MeshStandardMaterial( { roughness: 0.2, metalness: 0.85 } );
  1534. break;
  1535. default:
  1536. // Should not happen
  1537. break;
  1538. }
  1539. material.color.setStyle( fillColor, COLOR_SPACE_LDRAW );
  1540. material.transparent = isTransparent;
  1541. material.premultipliedAlpha = true;
  1542. material.opacity = alpha;
  1543. material.depthWrite = ! isTransparent;
  1544. material.polygonOffset = true;
  1545. material.polygonOffsetFactor = 1;
  1546. if ( luminance !== 0 ) {
  1547. material.emissive.setStyle( fillColor, COLOR_SPACE_LDRAW ).multiplyScalar( luminance );
  1548. }
  1549. if ( ! edgeMaterial ) {
  1550. // This is the material used for edges
  1551. edgeMaterial = new LineBasicMaterial( {
  1552. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1553. transparent: isTransparent,
  1554. opacity: alpha,
  1555. depthWrite: ! isTransparent
  1556. } );
  1557. edgeMaterial.color;
  1558. edgeMaterial.userData.code = code;
  1559. edgeMaterial.name = name + ' - Edge';
  1560. // This is the material used for conditional edges
  1561. const conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  1562. fog: true,
  1563. transparent: isTransparent,
  1564. depthWrite: ! isTransparent,
  1565. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1566. opacity: alpha,
  1567. } );
  1568. conditionalEdgeMaterial.userData.code = code;
  1569. conditionalEdgeMaterial.name = name + ' - Conditional Edge';
  1570. this.conditionalEdgeMaterialCache.set( edgeMaterial, conditionalEdgeMaterial );
  1571. }
  1572. material.userData.code = code;
  1573. material.name = name;
  1574. this.edgeMaterialCache.set( material, edgeMaterial );
  1575. this.addMaterial( material );
  1576. return material;
  1577. function parseLuminance( token ) {
  1578. // Returns success
  1579. let lum;
  1580. if ( token.startsWith( 'LUMINANCE' ) ) {
  1581. lum = parseInt( token.substring( 9 ) );
  1582. } else {
  1583. lum = parseInt( token );
  1584. }
  1585. if ( isNaN( lum ) ) {
  1586. return false;
  1587. }
  1588. luminance = Math.max( 0, Math.min( 1, lum / 255 ) );
  1589. return true;
  1590. }
  1591. }
  1592. computeBuildingSteps( model ) {
  1593. // Sets userdata.buildingStep number in Group objects and userData.numBuildingSteps number in the root Group object.
  1594. let stepNumber = 0;
  1595. model.traverse( c => {
  1596. if ( c.isGroup ) {
  1597. if ( c.userData.startingBuildingStep ) {
  1598. stepNumber ++;
  1599. }
  1600. c.userData.buildingStep = stepNumber;
  1601. }
  1602. } );
  1603. model.userData.numBuildingSteps = stepNumber + 1;
  1604. }
  1605. }
  1606. export { LDrawLoader };