LDrawLoader.js 59 KB

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