2
0

LDrawLoader.js 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  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_TRY_PARTS = 0;
  11. const FILE_LOCATION_TRY_P = 1;
  12. const FILE_LOCATION_TRY_MODELS = 2;
  13. const FILE_LOCATION_AS_IS = 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.author = original.author;
  431. result.subobjects = original.subobjects;
  432. result.fileName = original.fileName;
  433. result.totalFaces = original.totalFaces;
  434. result.startingConstructionStep = original.startingConstructionStep;
  435. result.materials = original.materials;
  436. result.group = null;
  437. return result;
  438. }
  439. async fetchData( fileName ) {
  440. let triedLowerCase = false;
  441. let locationState = FILE_LOCATION_TRY_PARTS;
  442. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  443. let subobjectURL = fileName;
  444. switch ( locationState ) {
  445. case FILE_LOCATION_AS_IS:
  446. locationState = locationState + 1;
  447. break;
  448. case FILE_LOCATION_TRY_PARTS:
  449. subobjectURL = 'parts/' + subobjectURL;
  450. locationState = locationState + 1;
  451. break;
  452. case FILE_LOCATION_TRY_P:
  453. subobjectURL = 'p/' + subobjectURL;
  454. locationState = locationState + 1;
  455. break;
  456. case FILE_LOCATION_TRY_MODELS:
  457. subobjectURL = 'models/' + subobjectURL;
  458. locationState = locationState + 1;
  459. break;
  460. case FILE_LOCATION_TRY_RELATIVE:
  461. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  462. locationState = locationState + 1;
  463. break;
  464. case FILE_LOCATION_TRY_ABSOLUTE:
  465. if ( triedLowerCase ) {
  466. // Try absolute path
  467. locationState = FILE_LOCATION_NOT_FOUND;
  468. } else {
  469. // Next attempt is lower case
  470. fileName = fileName.toLowerCase();
  471. subobjectURL = fileName;
  472. triedLowerCase = true;
  473. locationState = FILE_LOCATION_TRY_PARTS;
  474. }
  475. break;
  476. }
  477. const loader = this.loader;
  478. const fileLoader = new THREE.FileLoader( loader.manager );
  479. fileLoader.setPath( loader.partsLibraryPath );
  480. fileLoader.setRequestHeader( loader.requestHeader );
  481. fileLoader.setWithCredentials( loader.withCredentials );
  482. try {
  483. const text = await fileLoader.loadAsync( subobjectURL );
  484. return text;
  485. } catch {
  486. continue;
  487. }
  488. }
  489. throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
  490. }
  491. parse( text, fileName = null ) {
  492. const loader = this.loader; // final results
  493. const faces = [];
  494. const lineSegments = [];
  495. const conditionalSegments = [];
  496. const subobjects = [];
  497. const materials = {};
  498. const getLocalMaterial = colorCode => {
  499. return materials[ colorCode ] || null;
  500. };
  501. let type = 'Model';
  502. let category = null;
  503. let keywords = null;
  504. let author = null;
  505. let totalFaces = 0; // split into lines
  506. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  507. // This is faster than String.split with regex that splits on both
  508. text = text.replace( /\r\n/g, '\n' );
  509. }
  510. const lines = text.split( '\n' );
  511. const numLines = lines.length;
  512. let parsingEmbeddedFiles = false;
  513. let currentEmbeddedFileName = null;
  514. let currentEmbeddedText = null;
  515. let bfcCertified = false;
  516. let bfcCCW = true;
  517. let bfcInverted = false;
  518. let bfcCull = true;
  519. let startingConstructionStep = false; // Parse all line commands
  520. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  521. const line = lines[ lineIndex ];
  522. if ( line.length === 0 ) continue;
  523. if ( parsingEmbeddedFiles ) {
  524. if ( line.startsWith( '0 FILE ' ) ) {
  525. // Save previous embedded file in the cache
  526. this.setData( currentEmbeddedFileName, currentEmbeddedText ); // New embedded text file
  527. currentEmbeddedFileName = line.substring( 7 );
  528. currentEmbeddedText = '';
  529. } else {
  530. currentEmbeddedText += line + '\n';
  531. }
  532. continue;
  533. }
  534. const lp = new LineParser( line, lineIndex + 1 );
  535. lp.seekNonSpace();
  536. if ( lp.isAtTheEnd() ) {
  537. // Empty line
  538. continue;
  539. } // Parse the line type
  540. const lineType = lp.getToken();
  541. let material;
  542. let colorCode;
  543. let segment;
  544. let ccw;
  545. let doubleSided;
  546. let v0, v1, v2, v3, c0, c1;
  547. switch ( lineType ) {
  548. // Line type 0: Comment or META
  549. case '0':
  550. // Parse meta directive
  551. const meta = lp.getToken();
  552. if ( meta ) {
  553. switch ( meta ) {
  554. case '!LDRAW_ORG':
  555. type = lp.getToken();
  556. break;
  557. case '!COLOUR':
  558. material = loader.parseColorMetaDirective( lp );
  559. if ( material ) {
  560. materials[ material.userData.code ] = material;
  561. } else {
  562. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  563. }
  564. break;
  565. case '!CATEGORY':
  566. category = lp.getToken();
  567. break;
  568. case '!KEYWORDS':
  569. const newKeywords = lp.getRemainingString().split( ',' );
  570. if ( newKeywords.length > 0 ) {
  571. if ( ! keywords ) {
  572. keywords = [];
  573. }
  574. newKeywords.forEach( function ( keyword ) {
  575. keywords.push( keyword.trim() );
  576. } );
  577. }
  578. break;
  579. case 'FILE':
  580. if ( lineIndex > 0 ) {
  581. // Start embedded text files parsing
  582. parsingEmbeddedFiles = true;
  583. currentEmbeddedFileName = lp.getRemainingString();
  584. currentEmbeddedText = '';
  585. bfcCertified = false;
  586. bfcCCW = true;
  587. }
  588. break;
  589. case 'BFC':
  590. // Changes to the backface culling state
  591. while ( ! lp.isAtTheEnd() ) {
  592. const token = lp.getToken();
  593. switch ( token ) {
  594. case 'CERTIFY':
  595. case 'NOCERTIFY':
  596. bfcCertified = token === 'CERTIFY';
  597. bfcCCW = true;
  598. break;
  599. case 'CW':
  600. case 'CCW':
  601. bfcCCW = token === 'CCW';
  602. break;
  603. case 'INVERTNEXT':
  604. bfcInverted = true;
  605. break;
  606. case 'CLIP':
  607. case 'NOCLIP':
  608. bfcCull = token === 'CLIP';
  609. break;
  610. default:
  611. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  612. break;
  613. }
  614. }
  615. break;
  616. case 'STEP':
  617. startingConstructionStep = true;
  618. break;
  619. case 'Author:':
  620. author = lp.getToken();
  621. break;
  622. default:
  623. // Other meta directives are not implemented
  624. break;
  625. }
  626. }
  627. break;
  628. // Line type 1: Sub-object file
  629. case '1':
  630. colorCode = lp.getToken();
  631. material = getLocalMaterial( colorCode );
  632. const posX = parseFloat( lp.getToken() );
  633. const posY = parseFloat( lp.getToken() );
  634. const posZ = parseFloat( lp.getToken() );
  635. const m0 = parseFloat( lp.getToken() );
  636. const m1 = parseFloat( lp.getToken() );
  637. const m2 = parseFloat( lp.getToken() );
  638. const m3 = parseFloat( lp.getToken() );
  639. const m4 = parseFloat( lp.getToken() );
  640. const m5 = parseFloat( lp.getToken() );
  641. const m6 = parseFloat( lp.getToken() );
  642. const m7 = parseFloat( lp.getToken() );
  643. const m8 = parseFloat( lp.getToken() );
  644. const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
  645. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  646. if ( loader.fileMap[ fileName ] ) {
  647. // Found the subobject path in the preloaded file path map
  648. fileName = loader.fileMap[ fileName ];
  649. } else {
  650. // Standardized subfolders
  651. if ( fileName.startsWith( 's/' ) ) {
  652. fileName = 'parts/' + fileName;
  653. } else if ( fileName.startsWith( '48/' ) ) {
  654. fileName = 'p/' + fileName;
  655. }
  656. }
  657. subobjects.push( {
  658. material: material,
  659. colorCode: colorCode,
  660. matrix: matrix,
  661. fileName: fileName,
  662. inverted: bfcInverted,
  663. startingConstructionStep: startingConstructionStep
  664. } );
  665. bfcInverted = false;
  666. break;
  667. // Line type 2: Line segment
  668. case '2':
  669. colorCode = lp.getToken();
  670. material = getLocalMaterial( colorCode );
  671. v0 = lp.getVector();
  672. v1 = lp.getVector();
  673. segment = {
  674. material: material,
  675. colorCode: colorCode,
  676. vertices: [ v0, v1 ]
  677. };
  678. lineSegments.push( segment );
  679. break;
  680. // Line type 5: Conditional Line segment
  681. case '5':
  682. colorCode = lp.getToken();
  683. material = getLocalMaterial( colorCode );
  684. v0 = lp.getVector();
  685. v1 = lp.getVector();
  686. c0 = lp.getVector();
  687. c1 = lp.getVector();
  688. segment = {
  689. material: material,
  690. colorCode: colorCode,
  691. vertices: [ v0, v1 ],
  692. controlPoints: [ c0, c1 ]
  693. };
  694. conditionalSegments.push( segment );
  695. break;
  696. // Line type 3: Triangle
  697. case '3':
  698. colorCode = lp.getToken();
  699. material = getLocalMaterial( colorCode );
  700. ccw = bfcCCW;
  701. doubleSided = ! bfcCertified || ! bfcCull;
  702. if ( ccw === true ) {
  703. v0 = lp.getVector();
  704. v1 = lp.getVector();
  705. v2 = lp.getVector();
  706. } else {
  707. v2 = lp.getVector();
  708. v1 = lp.getVector();
  709. v0 = lp.getVector();
  710. }
  711. faces.push( {
  712. material: material,
  713. colorCode: colorCode,
  714. faceNormal: null,
  715. vertices: [ v0, v1, v2 ],
  716. normals: [ null, null, null ]
  717. } );
  718. totalFaces ++;
  719. if ( doubleSided === true ) {
  720. faces.push( {
  721. material: material,
  722. colorCode: colorCode,
  723. faceNormal: null,
  724. vertices: [ v2, v1, v0 ],
  725. normals: [ null, null, null ]
  726. } );
  727. totalFaces ++;
  728. }
  729. break;
  730. // Line type 4: Quadrilateral
  731. case '4':
  732. colorCode = lp.getToken();
  733. material = getLocalMaterial( colorCode );
  734. ccw = bfcCCW;
  735. doubleSided = ! bfcCertified || ! bfcCull;
  736. if ( ccw === true ) {
  737. v0 = lp.getVector();
  738. v1 = lp.getVector();
  739. v2 = lp.getVector();
  740. v3 = lp.getVector();
  741. } else {
  742. v3 = lp.getVector();
  743. v2 = lp.getVector();
  744. v1 = lp.getVector();
  745. v0 = lp.getVector();
  746. } // specifically place the triangle diagonal in the v0 and v1 slots so we can
  747. // account for the doubling of vertices later when smoothing normals.
  748. faces.push( {
  749. material: material,
  750. colorCode: colorCode,
  751. faceNormal: null,
  752. vertices: [ v0, v1, v2, v3 ],
  753. normals: [ null, null, null, null ]
  754. } );
  755. totalFaces += 2;
  756. if ( doubleSided === true ) {
  757. faces.push( {
  758. material: material,
  759. colorCode: colorCode,
  760. faceNormal: null,
  761. vertices: [ v3, v2, v1, v0 ],
  762. normals: [ null, null, null, null ]
  763. } );
  764. totalFaces += 2;
  765. }
  766. break;
  767. default:
  768. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  769. }
  770. }
  771. if ( parsingEmbeddedFiles ) {
  772. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  773. }
  774. return {
  775. faces,
  776. conditionalSegments,
  777. lineSegments,
  778. type,
  779. category,
  780. keywords,
  781. author,
  782. subobjects,
  783. totalFaces,
  784. startingConstructionStep,
  785. materials,
  786. fileName,
  787. group: null
  788. };
  789. } // returns an (optionally cloned) instance of the data
  790. getData( fileName, clone = true ) {
  791. const key = fileName.toLowerCase();
  792. const result = this._cache[ key ];
  793. if ( result === null || result instanceof Promise ) {
  794. return null;
  795. }
  796. if ( clone ) {
  797. return this.cloneResult( result );
  798. } else {
  799. return result;
  800. }
  801. } // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  802. // the data is ready to use and can be retrieved synchronously with "getData".
  803. async ensureDataLoaded( fileName ) {
  804. const key = fileName.toLowerCase();
  805. if ( ! ( key in this._cache ) ) {
  806. // replace the promise with a copy of the parsed data for immediate processing
  807. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  808. const info = this.parse( text, fileName );
  809. this._cache[ key ] = info;
  810. return info;
  811. } );
  812. }
  813. await this._cache[ key ];
  814. } // sets the data in the cache from parsed data
  815. setData( fileName, text ) {
  816. const key = fileName.toLowerCase();
  817. this._cache[ key ] = this.parse( text, fileName );
  818. }
  819. } // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  820. // an edge then the passthroughColorCode is used.
  821. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  822. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  823. if ( isPassthrough ) {
  824. colorCode = parentColorCode;
  825. }
  826. return materialHierarchy[ colorCode ] || null;
  827. } // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  828. class LDrawPartsGeometryCache {
  829. constructor( loader ) {
  830. this.loader = loader;
  831. this.parseCache = new LDrawParsedCache( loader );
  832. this._cache = {};
  833. } // Convert the given file information into a mesh by processing subobjects.
  834. async processIntoMesh( info ) {
  835. const loader = this.loader;
  836. const parseCache = this.parseCache;
  837. const faceMaterials = new Set(); // Processes the part subobject information to load child parts and merge geometry onto part
  838. // piece object.
  839. const processInfoSubobjects = async ( info, subobject = null ) => {
  840. const subobjects = info.subobjects;
  841. const promises = []; // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  842. // group which lets instruction steps apply correctly.
  843. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  844. const subobject = subobjects[ i ];
  845. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  846. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  847. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  848. return this.loadModel( subobject.fileName ).catch( error => {
  849. console.warn( error );
  850. return null;
  851. } );
  852. }
  853. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  854. } );
  855. promises.push( promise );
  856. }
  857. const group = new THREE.Group();
  858. group.userData.category = info.category;
  859. group.userData.keywords = info.keywords;
  860. group.userData.author = info.author;
  861. group.userData.type = info.type;
  862. group.userData.fileName = info.fileName;
  863. info.group = group;
  864. const subobjectInfos = await Promise.all( promises );
  865. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  866. const subobject = info.subobjects[ i ];
  867. const subobjectInfo = subobjectInfos[ i ];
  868. if ( subobjectInfo === null ) {
  869. // the subobject failed to load
  870. continue;
  871. } // if the subobject was loaded as a separate group then apply the parent scopes materials
  872. if ( subobjectInfo.isGroup ) {
  873. const subobjectGroup = subobjectInfo;
  874. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  875. subobjectGroup.userData.startingConstructionStep = subobject.startingConstructionStep;
  876. subobjectGroup.name = subobject.fileName;
  877. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  878. subobjectGroup.userData.colorCode = subobject.colorCode;
  879. group.add( subobjectGroup );
  880. continue;
  881. } // add the subobject group if it has children in case it has both children and primitives
  882. if ( subobjectInfo.group.children.length ) {
  883. group.add( subobjectInfo.group );
  884. } // transform the primitives into the local space of the parent piece and append them to
  885. // to the parent primitives list.
  886. const parentLineSegments = info.lineSegments;
  887. const parentConditionalSegments = info.conditionalSegments;
  888. const parentFaces = info.faces;
  889. const lineSegments = subobjectInfo.lineSegments;
  890. const conditionalSegments = subobjectInfo.conditionalSegments;
  891. const faces = subobjectInfo.faces;
  892. const matrix = subobject.matrix;
  893. const inverted = subobject.inverted;
  894. const matrixScaleInverted = matrix.determinant() < 0;
  895. const colorCode = subobject.colorCode;
  896. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  897. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  898. const ls = lineSegments[ i ];
  899. const vertices = ls.vertices;
  900. vertices[ 0 ].applyMatrix4( matrix );
  901. vertices[ 1 ].applyMatrix4( matrix );
  902. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  903. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  904. parentLineSegments.push( ls );
  905. }
  906. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  907. const os = conditionalSegments[ i ];
  908. const vertices = os.vertices;
  909. const controlPoints = os.controlPoints;
  910. vertices[ 0 ].applyMatrix4( matrix );
  911. vertices[ 1 ].applyMatrix4( matrix );
  912. controlPoints[ 0 ].applyMatrix4( matrix );
  913. controlPoints[ 1 ].applyMatrix4( matrix );
  914. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  915. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  916. parentConditionalSegments.push( os );
  917. }
  918. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  919. const tri = faces[ i ];
  920. const vertices = tri.vertices;
  921. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  922. vertices[ i ].applyMatrix4( matrix );
  923. }
  924. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  925. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  926. faceMaterials.add( tri.colorCode ); // If the scale of the object is negated then the triangle winding order
  927. // needs to be flipped.
  928. if ( matrixScaleInverted !== inverted ) {
  929. vertices.reverse();
  930. }
  931. parentFaces.push( tri );
  932. }
  933. info.totalFaces += subobjectInfo.totalFaces;
  934. } // Apply the parent subobjects pass through material code to this object. This is done several times due
  935. // to material scoping.
  936. if ( subobject ) {
  937. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  938. group.userData.colorCode = subobject.colorCode;
  939. }
  940. return info;
  941. }; // Track material use to see if we need to use the normal smooth slow path for hard edges.
  942. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  943. faceMaterials.add( info.faces[ i ].colorCode );
  944. }
  945. await processInfoSubobjects( info );
  946. if ( loader.smoothNormals ) {
  947. const checkSubSegments = faceMaterials.size > 1;
  948. generateFaceNormals( info.faces );
  949. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  950. } // Add the primitive objects and metadata.
  951. const group = info.group;
  952. if ( info.faces.length > 0 ) {
  953. group.add( createObject( info.faces, 3, false, info.totalFaces ) );
  954. }
  955. if ( info.lineSegments.length > 0 ) {
  956. group.add( createObject( info.lineSegments, 2 ) );
  957. }
  958. if ( info.conditionalSegments.length > 0 ) {
  959. group.add( createObject( info.conditionalSegments, 2, true ) );
  960. }
  961. return group;
  962. }
  963. hasCachedModel( fileName ) {
  964. return fileName !== null && fileName.toLowerCase() in this._cache;
  965. }
  966. async getCachedModel( fileName ) {
  967. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  968. const key = fileName.toLowerCase();
  969. const group = await this._cache[ key ];
  970. return group.clone();
  971. } else {
  972. return null;
  973. }
  974. } // Loads and parses the model with the given file name. Returns a cached copy if available.
  975. async loadModel( fileName ) {
  976. const parseCache = this.parseCache;
  977. const key = fileName.toLowerCase();
  978. if ( this.hasCachedModel( fileName ) ) {
  979. // Return cached model if available.
  980. return this.getCachedModel( fileName );
  981. } else {
  982. // Otherwise parse a new model.
  983. // Ensure the file data is loaded and pre parsed.
  984. await parseCache.ensureDataLoaded( fileName );
  985. const info = parseCache.getData( fileName );
  986. const promise = this.processIntoMesh( info ); // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  987. // so check the cache again to see if it's been added since the last async operation so we don't
  988. // do unnecessary work.
  989. if ( this.hasCachedModel( fileName ) ) {
  990. return this.getCachedModel( fileName );
  991. } // Cache object if it's a part so it can be reused later.
  992. if ( isPartType( info.type ) ) {
  993. this._cache[ key ] = promise;
  994. } // return a copy
  995. const group = await promise;
  996. return group.clone();
  997. }
  998. } // parses the given model text into a renderable object. Returns cached copy if available.
  999. async parseModel( text ) {
  1000. const parseCache = this.parseCache;
  1001. const info = parseCache.parse( text );
  1002. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  1003. return this.getCachedModel( info.fileName );
  1004. }
  1005. return this.processIntoMesh( info );
  1006. }
  1007. }
  1008. function sortByMaterial( a, b ) {
  1009. if ( a.colorCode === b.colorCode ) {
  1010. return 0;
  1011. }
  1012. if ( a.colorCode < b.colorCode ) {
  1013. return - 1;
  1014. }
  1015. return 1;
  1016. }
  1017. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  1018. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  1019. // With per face / segment material, implemented with mesh groups and materials array
  1020. // Sort the faces or line segments by color code to make later the mesh groups
  1021. elements.sort( sortByMaterial );
  1022. if ( totalElements === null ) {
  1023. totalElements = elements.length;
  1024. }
  1025. const positions = new Float32Array( elementSize * totalElements * 3 );
  1026. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1027. const materials = [];
  1028. const quadArray = new Array( 6 );
  1029. const bufferGeometry = new THREE.BufferGeometry();
  1030. let prevMaterial = null;
  1031. let index0 = 0;
  1032. let numGroupVerts = 0;
  1033. let offset = 0;
  1034. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1035. const elem = elements[ iElem ];
  1036. let vertices = elem.vertices;
  1037. if ( vertices.length === 4 ) {
  1038. quadArray[ 0 ] = vertices[ 0 ];
  1039. quadArray[ 1 ] = vertices[ 1 ];
  1040. quadArray[ 2 ] = vertices[ 2 ];
  1041. quadArray[ 3 ] = vertices[ 0 ];
  1042. quadArray[ 4 ] = vertices[ 2 ];
  1043. quadArray[ 5 ] = vertices[ 3 ];
  1044. vertices = quadArray;
  1045. }
  1046. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1047. const v = vertices[ j ];
  1048. const index = offset + j * 3;
  1049. positions[ index + 0 ] = v.x;
  1050. positions[ index + 1 ] = v.y;
  1051. positions[ index + 2 ] = v.z;
  1052. } // create the normals array if this is a set of faces
  1053. if ( elementSize === 3 ) {
  1054. if ( ! elem.faceNormal ) {
  1055. const v0 = vertices[ 0 ];
  1056. const v1 = vertices[ 1 ];
  1057. const v2 = vertices[ 2 ];
  1058. _tempVec0.subVectors( v1, v0 );
  1059. _tempVec1.subVectors( v2, v1 );
  1060. elem.faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  1061. }
  1062. let elemNormals = elem.normals;
  1063. if ( elemNormals.length === 4 ) {
  1064. quadArray[ 0 ] = elemNormals[ 0 ];
  1065. quadArray[ 1 ] = elemNormals[ 1 ];
  1066. quadArray[ 2 ] = elemNormals[ 2 ];
  1067. quadArray[ 3 ] = elemNormals[ 0 ];
  1068. quadArray[ 4 ] = elemNormals[ 2 ];
  1069. quadArray[ 5 ] = elemNormals[ 3 ];
  1070. elemNormals = quadArray;
  1071. }
  1072. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1073. // use face normal if a vertex normal is not provided
  1074. let n = elem.faceNormal;
  1075. if ( elemNormals[ j ] ) {
  1076. n = elemNormals[ j ].norm;
  1077. }
  1078. const index = offset + j * 3;
  1079. normals[ index + 0 ] = n.x;
  1080. normals[ index + 1 ] = n.y;
  1081. normals[ index + 2 ] = n.z;
  1082. }
  1083. }
  1084. if ( prevMaterial !== elem.colorCode ) {
  1085. if ( prevMaterial !== null ) {
  1086. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1087. }
  1088. const material = elem.material;
  1089. if ( material !== null ) {
  1090. if ( elementSize === 3 ) {
  1091. materials.push( material );
  1092. } else if ( elementSize === 2 ) {
  1093. if ( isConditionalSegments ) {
  1094. materials.push( material.userData.edgeMaterial.userData.conditionalEdgeMaterial );
  1095. } else {
  1096. materials.push( material.userData.edgeMaterial );
  1097. }
  1098. }
  1099. } else {
  1100. // If a material has not been made available yet then keep the color code string in the material array
  1101. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1102. materials.push( elem.colorCode );
  1103. }
  1104. prevMaterial = elem.colorCode;
  1105. index0 = offset / 3;
  1106. numGroupVerts = vertices.length;
  1107. } else {
  1108. numGroupVerts += vertices.length;
  1109. }
  1110. offset += 3 * vertices.length;
  1111. }
  1112. if ( numGroupVerts > 0 ) {
  1113. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1114. }
  1115. bufferGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  1116. if ( normals !== null ) {
  1117. bufferGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  1118. }
  1119. let object3d = null;
  1120. if ( elementSize === 2 ) {
  1121. if ( isConditionalSegments ) {
  1122. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1123. } else {
  1124. object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1125. }
  1126. } else if ( elementSize === 3 ) {
  1127. object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1128. }
  1129. if ( isConditionalSegments ) {
  1130. object3d.isConditionalLine = true;
  1131. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1132. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1133. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1134. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1135. const os = elements[ i ];
  1136. const vertices = os.vertices;
  1137. const controlPoints = os.controlPoints;
  1138. const c0 = controlPoints[ 0 ];
  1139. const c1 = controlPoints[ 1 ];
  1140. const v0 = vertices[ 0 ];
  1141. const v1 = vertices[ 1 ];
  1142. const index = i * 3 * 2;
  1143. controlArray0[ index + 0 ] = c0.x;
  1144. controlArray0[ index + 1 ] = c0.y;
  1145. controlArray0[ index + 2 ] = c0.z;
  1146. controlArray0[ index + 3 ] = c0.x;
  1147. controlArray0[ index + 4 ] = c0.y;
  1148. controlArray0[ index + 5 ] = c0.z;
  1149. controlArray1[ index + 0 ] = c1.x;
  1150. controlArray1[ index + 1 ] = c1.y;
  1151. controlArray1[ index + 2 ] = c1.z;
  1152. controlArray1[ index + 3 ] = c1.x;
  1153. controlArray1[ index + 4 ] = c1.y;
  1154. controlArray1[ index + 5 ] = c1.z;
  1155. directionArray[ index + 0 ] = v1.x - v0.x;
  1156. directionArray[ index + 1 ] = v1.y - v0.y;
  1157. directionArray[ index + 2 ] = v1.z - v0.z;
  1158. directionArray[ index + 3 ] = v1.x - v0.x;
  1159. directionArray[ index + 4 ] = v1.y - v0.y;
  1160. directionArray[ index + 5 ] = v1.z - v0.z;
  1161. }
  1162. bufferGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  1163. bufferGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  1164. bufferGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  1165. }
  1166. return object3d;
  1167. } //
  1168. class LDrawLoader extends THREE.Loader {
  1169. constructor( manager ) {
  1170. super( manager ); // Array of THREE.Material
  1171. this.materials = [];
  1172. this.materialLibrary = {}; // This also allows to handle the embedded text files ("0 FILE" lines)
  1173. 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.
  1174. this.fileMap = {}; // Initializes the materials library with default materials
  1175. this.setMaterials( [] ); // If this flag is set to true the vertex normals will be smoothed.
  1176. this.smoothNormals = true; // The path to load parts from the LDraw parts library from.
  1177. this.partsLibraryPath = ''; // Material assigned to not available colors for meshes and edges
  1178. this.missingColorMaterial = new THREE.MeshStandardMaterial( {
  1179. color: 0xFF00FF,
  1180. roughness: 0.3,
  1181. metalness: 0
  1182. } );
  1183. this.missingColorMaterial.name = 'Missing material';
  1184. this.missingEdgeColorMaterial = new THREE.LineBasicMaterial( {
  1185. color: 0xFF00FF
  1186. } );
  1187. this.missingEdgeColorMaterial.name = 'Missing material - Edge';
  1188. this.missingConditionalEdgeColorMaterial = new LDrawConditionalLineMaterial( {
  1189. fog: true,
  1190. color: 0xFF00FF
  1191. } );
  1192. this.missingConditionalEdgeColorMaterial.name = 'Missing material - Conditional Edge';
  1193. this.missingColorMaterial.userData.edgeMaterial = this.missingEdgeColorMaterial;
  1194. this.missingEdgeColorMaterial.userData.conditionalEdgeMaterial = this.missingConditionalEdgeColorMaterial;
  1195. }
  1196. setPartsLibraryPath( path ) {
  1197. this.partsLibraryPath = path;
  1198. return this;
  1199. }
  1200. async preloadMaterials( url ) {
  1201. const fileLoader = new THREE.FileLoader( this.manager );
  1202. fileLoader.setPath( this.path );
  1203. fileLoader.setRequestHeader( this.requestHeader );
  1204. fileLoader.setWithCredentials( this.withCredentials );
  1205. const text = await fileLoader.loadAsync( url );
  1206. const colorLineRegex = /^0 !COLOUR/;
  1207. const lines = text.split( /[\n\r]/g );
  1208. const materials = [];
  1209. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1210. const line = lines[ i ];
  1211. if ( colorLineRegex.test( line ) ) {
  1212. const directive = line.replace( colorLineRegex, '' );
  1213. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1214. materials.push( material );
  1215. }
  1216. }
  1217. this.setMaterials( materials );
  1218. }
  1219. load( url, onLoad, onProgress, onError ) {
  1220. const fileLoader = new THREE.FileLoader( this.manager );
  1221. fileLoader.setPath( this.path );
  1222. fileLoader.setRequestHeader( this.requestHeader );
  1223. fileLoader.setWithCredentials( this.withCredentials );
  1224. fileLoader.load( url, text => {
  1225. this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
  1226. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1227. this.computeConstructionSteps( group );
  1228. group.userData.fileName = url;
  1229. onLoad( group );
  1230. } ).catch( onError );
  1231. }, onProgress, onError );
  1232. }
  1233. parse( text, onLoad ) {
  1234. this.partsCache.parseModel( text, this.materialLibrary ).then( group => {
  1235. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1236. this.computeConstructionSteps( group );
  1237. group.userData.fileName = '';
  1238. onLoad( group );
  1239. } );
  1240. }
  1241. setMaterials( materials ) {
  1242. this.materialLibrary = {};
  1243. this.materials = [];
  1244. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1245. this.addMaterial( materials[ i ] );
  1246. } // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1247. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1248. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1249. return this;
  1250. }
  1251. setFileMap( fileMap ) {
  1252. this.fileMap = fileMap;
  1253. return this;
  1254. }
  1255. addMaterial( material ) {
  1256. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1257. const matLib = this.materialLibrary;
  1258. if ( ! matLib[ material.userData.code ] ) {
  1259. this.materials.push( material );
  1260. matLib[ material.userData.code ] = material;
  1261. }
  1262. return this;
  1263. }
  1264. getMaterial( colorCode ) {
  1265. if ( colorCode.startsWith( '0x2' ) ) {
  1266. // Special 'direct' material value (RGB color)
  1267. const color = colorCode.substring( 3 );
  1268. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1269. }
  1270. return this.materialLibrary[ colorCode ] || null;
  1271. } // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1272. // in the material array if they need to be filled in.
  1273. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1274. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1275. const loader = this;
  1276. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1277. group.traverse( c => {
  1278. if ( c.isMesh || c.isLineSegments ) {
  1279. if ( Array.isArray( c.material ) ) {
  1280. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1281. if ( ! c.material[ i ].isMaterial ) {
  1282. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1283. }
  1284. }
  1285. } else if ( ! c.material.isMaterial ) {
  1286. c.material = getMaterial( c, c.material );
  1287. }
  1288. }
  1289. } ); // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1290. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1291. // simply returned for the subsequent material application.
  1292. function getMaterial( c, colorCode ) {
  1293. // if our parent is a passthrough color code and we don't have the current material color available then
  1294. // return early.
  1295. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1296. return colorCode;
  1297. }
  1298. const forEdge = c.isLineSegments || c.isConditionalLine;
  1299. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1300. if ( isPassthrough ) {
  1301. colorCode = parentColorCode;
  1302. }
  1303. let material = null;
  1304. if ( colorCode in materialHierarchy ) {
  1305. material = materialHierarchy[ colorCode ];
  1306. } else if ( finalMaterialPass ) {
  1307. // see if we can get the final material from from the "getMaterial" function which will attempt to
  1308. // parse the "direct" colors
  1309. material = loader.getMaterial( colorCode );
  1310. if ( material === null ) {
  1311. // otherwise throw a warning if this is final opportunity to set the material
  1312. console.warn( `LDrawLoader: Material properties for code ${colorCode} not available.` ); // And return the 'missing color' material
  1313. material = loader.missingColorMaterial;
  1314. }
  1315. } else {
  1316. return colorCode;
  1317. }
  1318. if ( c.isLineSegments ) {
  1319. material = material.userData.edgeMaterial;
  1320. if ( c.isConditionalLine ) {
  1321. material = material.userData.conditionalEdgeMaterial;
  1322. }
  1323. }
  1324. return material;
  1325. }
  1326. }
  1327. getMainMaterial() {
  1328. return this.getMaterial( MAIN_COLOUR_CODE );
  1329. }
  1330. getMainEdgeMaterial() {
  1331. const mat = this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1332. return mat ? mat.userData.edgeMaterial : null;
  1333. }
  1334. parseColorMetaDirective( lineParser ) {
  1335. // Parses a color definition and returns a THREE.Material
  1336. let code = null; // Triangle and line colors
  1337. let color = 0xFF00FF;
  1338. let edgeColor = 0xFF00FF; // Transparency
  1339. let alpha = 1;
  1340. let isTransparent = false; // Self-illumination:
  1341. let luminance = 0;
  1342. let finishType = FINISH_TYPE_DEFAULT;
  1343. let edgeMaterial = null;
  1344. const name = lineParser.getToken();
  1345. if ( ! name ) {
  1346. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  1347. } // Parse tag tokens and their parameters
  1348. let token = null;
  1349. while ( true ) {
  1350. token = lineParser.getToken();
  1351. if ( ! token ) {
  1352. break;
  1353. }
  1354. if ( ! parseLuminance( token ) ) {
  1355. switch ( token.toUpperCase() ) {
  1356. case 'CODE':
  1357. code = lineParser.getToken();
  1358. break;
  1359. case 'VALUE':
  1360. color = lineParser.getToken();
  1361. if ( color.startsWith( '0x' ) ) {
  1362. color = '#' + color.substring( 2 );
  1363. } else if ( ! color.startsWith( '#' ) ) {
  1364. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1365. }
  1366. break;
  1367. case 'EDGE':
  1368. edgeColor = lineParser.getToken();
  1369. if ( edgeColor.startsWith( '0x' ) ) {
  1370. edgeColor = '#' + edgeColor.substring( 2 );
  1371. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1372. // Try to see if edge color is a color code
  1373. edgeMaterial = this.getMaterial( edgeColor );
  1374. if ( ! edgeMaterial ) {
  1375. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1376. } // Get the edge material for this triangle material
  1377. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  1378. }
  1379. break;
  1380. case 'ALPHA':
  1381. alpha = parseInt( lineParser.getToken() );
  1382. if ( isNaN( alpha ) ) {
  1383. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1384. }
  1385. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1386. if ( alpha < 1 ) {
  1387. isTransparent = true;
  1388. }
  1389. break;
  1390. case 'LUMINANCE':
  1391. if ( ! parseLuminance( lineParser.getToken() ) ) {
  1392. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  1393. }
  1394. break;
  1395. case 'CHROME':
  1396. finishType = FINISH_TYPE_CHROME;
  1397. break;
  1398. case 'PEARLESCENT':
  1399. finishType = FINISH_TYPE_PEARLESCENT;
  1400. break;
  1401. case 'RUBBER':
  1402. finishType = FINISH_TYPE_RUBBER;
  1403. break;
  1404. case 'MATTE_METALLIC':
  1405. finishType = FINISH_TYPE_MATTE_METALLIC;
  1406. break;
  1407. case 'METAL':
  1408. finishType = FINISH_TYPE_METAL;
  1409. break;
  1410. case 'MATERIAL':
  1411. // Not implemented
  1412. lineParser.setToEnd();
  1413. break;
  1414. default:
  1415. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1416. }
  1417. }
  1418. }
  1419. let material = null;
  1420. switch ( finishType ) {
  1421. case FINISH_TYPE_DEFAULT:
  1422. material = new THREE.MeshStandardMaterial( {
  1423. color: color,
  1424. roughness: 0.3,
  1425. metalness: 0
  1426. } );
  1427. break;
  1428. case FINISH_TYPE_PEARLESCENT:
  1429. // Try to imitate pearlescency by making the surface glossy
  1430. material = new THREE.MeshStandardMaterial( {
  1431. color: color,
  1432. roughness: 0.3,
  1433. metalness: 0.25
  1434. } );
  1435. break;
  1436. case FINISH_TYPE_CHROME:
  1437. // Mirror finish surface
  1438. material = new THREE.MeshStandardMaterial( {
  1439. color: color,
  1440. roughness: 0,
  1441. metalness: 1
  1442. } );
  1443. break;
  1444. case FINISH_TYPE_RUBBER:
  1445. // Rubber finish
  1446. material = new THREE.MeshStandardMaterial( {
  1447. color: color,
  1448. roughness: 0.9,
  1449. metalness: 0
  1450. } );
  1451. break;
  1452. case FINISH_TYPE_MATTE_METALLIC:
  1453. // Brushed metal finish
  1454. material = new THREE.MeshStandardMaterial( {
  1455. color: color,
  1456. roughness: 0.8,
  1457. metalness: 0.4
  1458. } );
  1459. break;
  1460. case FINISH_TYPE_METAL:
  1461. // Average metal finish
  1462. material = new THREE.MeshStandardMaterial( {
  1463. color: color,
  1464. roughness: 0.2,
  1465. metalness: 0.85
  1466. } );
  1467. break;
  1468. default:
  1469. // Should not happen
  1470. break;
  1471. }
  1472. material.transparent = isTransparent;
  1473. material.premultipliedAlpha = true;
  1474. material.opacity = alpha;
  1475. material.depthWrite = ! isTransparent;
  1476. material.color.convertSRGBToLinear();
  1477. material.polygonOffset = true;
  1478. material.polygonOffsetFactor = 1;
  1479. if ( luminance !== 0 ) {
  1480. material.emissive.set( material.color ).multiplyScalar( luminance );
  1481. }
  1482. if ( ! edgeMaterial ) {
  1483. // This is the material used for edges
  1484. edgeMaterial = new THREE.LineBasicMaterial( {
  1485. color: edgeColor,
  1486. transparent: isTransparent,
  1487. opacity: alpha,
  1488. depthWrite: ! isTransparent
  1489. } );
  1490. edgeMaterial.userData.code = code;
  1491. edgeMaterial.name = name + ' - Edge';
  1492. edgeMaterial.color.convertSRGBToLinear(); // This is the material used for conditional edges
  1493. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  1494. fog: true,
  1495. transparent: isTransparent,
  1496. depthWrite: ! isTransparent,
  1497. color: edgeColor,
  1498. opacity: alpha
  1499. } );
  1500. edgeMaterial.userData.conditionalEdgeMaterial.color.convertSRGBToLinear();
  1501. edgeMaterial.userData.conditionalEdgeMaterial.userData.code = code;
  1502. edgeMaterial.userData.conditionalEdgeMaterial.name = name + ' - Conditional Edge';
  1503. }
  1504. material.userData.code = code;
  1505. material.name = name;
  1506. material.userData.edgeMaterial = edgeMaterial;
  1507. this.addMaterial( material );
  1508. return material;
  1509. function parseLuminance( token ) {
  1510. // Returns success
  1511. let lum;
  1512. if ( token.startsWith( 'LUMINANCE' ) ) {
  1513. lum = parseInt( token.substring( 9 ) );
  1514. } else {
  1515. lum = parseInt( token );
  1516. }
  1517. if ( isNaN( lum ) ) {
  1518. return false;
  1519. }
  1520. luminance = Math.max( 0, Math.min( 1, lum / 255 ) );
  1521. return true;
  1522. }
  1523. }
  1524. computeConstructionSteps( model ) {
  1525. // Sets userdata.constructionStep number in THREE.Group objects and userData.numConstructionSteps number in the root THREE.Group object.
  1526. let stepNumber = 0;
  1527. model.traverse( c => {
  1528. if ( c.isGroup ) {
  1529. if ( c.userData.startingConstructionStep ) {
  1530. stepNumber ++;
  1531. }
  1532. c.userData.constructionStep = stepNumber;
  1533. }
  1534. } );
  1535. model.userData.numConstructionSteps = stepNumber + 1;
  1536. }
  1537. }
  1538. THREE.LDrawLoader = LDrawLoader;
  1539. } )();