LDrawLoader.js 55 KB

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