1
0

LDrawLoader.js 56 KB

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