LDrawLoader.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933
  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 _tempVec0 = new THREE.Vector3();
  18. const _tempVec1 = new THREE.Vector3();
  19. class LDrawConditionalLineMaterial extends THREE.ShaderMaterial {
  20. constructor( parameters ) {
  21. super( {
  22. uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib.fog, {
  23. diffuse: {
  24. value: new THREE.Color()
  25. },
  26. opacity: {
  27. value: 1.0
  28. }
  29. } ] ),
  30. vertexShader:
  31. /* glsl */
  32. `
  33. attribute vec3 control0;
  34. attribute vec3 control1;
  35. attribute vec3 direction;
  36. varying float discardFlag;
  37. #include <common>
  38. #include <color_pars_vertex>
  39. #include <fog_pars_vertex>
  40. #include <logdepthbuf_pars_vertex>
  41. #include <clipping_planes_pars_vertex>
  42. void main() {
  43. #include <color_vertex>
  44. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  45. gl_Position = projectionMatrix * mvPosition;
  46. // Transform the line segment ends and control points into camera clip space
  47. vec4 c0 = projectionMatrix * modelViewMatrix * vec4( control0, 1.0 );
  48. vec4 c1 = projectionMatrix * modelViewMatrix * vec4( control1, 1.0 );
  49. vec4 p0 = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  50. vec4 p1 = projectionMatrix * modelViewMatrix * vec4( position + direction, 1.0 );
  51. c0.xy /= c0.w;
  52. c1.xy /= c1.w;
  53. p0.xy /= p0.w;
  54. p1.xy /= p1.w;
  55. // Get the direction of the segment and an orthogonal vector
  56. vec2 dir = p1.xy - p0.xy;
  57. vec2 norm = vec2( -dir.y, dir.x );
  58. // Get control point directions from the line
  59. vec2 c0dir = c0.xy - p1.xy;
  60. vec2 c1dir = c1.xy - p1.xy;
  61. // If the vectors to the controls points are pointed in different directions away
  62. // from the line segment then the line should not be drawn.
  63. float d0 = dot( normalize( norm ), normalize( c0dir ) );
  64. float d1 = dot( normalize( norm ), normalize( c1dir ) );
  65. discardFlag = float( sign( d0 ) != sign( d1 ) );
  66. #include <logdepthbuf_vertex>
  67. #include <clipping_planes_vertex>
  68. #include <fog_vertex>
  69. }
  70. `,
  71. fragmentShader:
  72. /* glsl */
  73. `
  74. uniform vec3 diffuse;
  75. uniform float opacity;
  76. varying float discardFlag;
  77. #include <common>
  78. #include <color_pars_fragment>
  79. #include <fog_pars_fragment>
  80. #include <logdepthbuf_pars_fragment>
  81. #include <clipping_planes_pars_fragment>
  82. void main() {
  83. if ( discardFlag > 0.5 ) discard;
  84. #include <clipping_planes_fragment>
  85. vec3 outgoingLight = vec3( 0.0 );
  86. vec4 diffuseColor = vec4( diffuse, opacity );
  87. #include <logdepthbuf_fragment>
  88. #include <color_fragment>
  89. outgoingLight = diffuseColor.rgb; // simple shader
  90. gl_FragColor = vec4( outgoingLight, diffuseColor.a );
  91. #include <tonemapping_fragment>
  92. #include <encodings_fragment>
  93. #include <fog_fragment>
  94. #include <premultiplied_alpha_fragment>
  95. }
  96. `
  97. } );
  98. Object.defineProperties( this, {
  99. opacity: {
  100. get: function () {
  101. return this.uniforms.opacity.value;
  102. },
  103. set: function ( value ) {
  104. this.uniforms.opacity.value = value;
  105. }
  106. },
  107. color: {
  108. get: function () {
  109. return this.uniforms.diffuse.value;
  110. }
  111. }
  112. } );
  113. this.setValues( parameters );
  114. this.isLDrawConditionalLineMaterial = true;
  115. }
  116. }
  117. function smoothNormals( faces, lineSegments ) {
  118. function hashVertex( v ) {
  119. // NOTE: 1e2 is pretty coarse but was chosen because it allows edges
  120. // to be smoothed as expected (see minifig arms). The errors between edges
  121. // could be due to matrix multiplication.
  122. const x = ~ ~ ( v.x * 1e2 );
  123. const y = ~ ~ ( v.y * 1e2 );
  124. const z = ~ ~ ( v.z * 1e2 );
  125. return `${x},${y},${z}`;
  126. }
  127. function hashEdge( v0, v1 ) {
  128. return `${hashVertex( v0 )}_${hashVertex( v1 )}`;
  129. }
  130. const hardEdges = new Set();
  131. const halfEdgeList = {};
  132. const normals = []; // Save the list of hard edges by hash
  133. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  134. const ls = lineSegments[ i ];
  135. const vertices = ls.vertices;
  136. const v0 = vertices[ 0 ];
  137. const v1 = vertices[ 1 ];
  138. hardEdges.add( hashEdge( v0, v1 ) );
  139. hardEdges.add( hashEdge( v1, v0 ) );
  140. } // track the half edges associated with each triangle
  141. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  142. const tri = faces[ i ];
  143. const vertices = tri.vertices;
  144. const vertCount = vertices.length;
  145. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  146. const index = i2;
  147. const next = ( i2 + 1 ) % vertCount;
  148. const v0 = vertices[ index ];
  149. const v1 = vertices[ next ];
  150. const hash = hashEdge( v0, v1 ); // don't add the triangle if the edge is supposed to be hard
  151. if ( hardEdges.has( hash ) ) continue;
  152. const info = {
  153. index: index,
  154. tri: tri
  155. };
  156. halfEdgeList[ hash ] = info;
  157. }
  158. } // Iterate until we've tried to connect all faces to share normals
  159. while ( true ) {
  160. // Stop if there are no more faces left
  161. let halfEdge = null;
  162. for ( const key in halfEdgeList ) {
  163. halfEdge = halfEdgeList[ key ];
  164. break;
  165. }
  166. if ( halfEdge === null ) {
  167. break;
  168. } // Exhaustively find all connected faces
  169. const queue = [ halfEdge ];
  170. while ( queue.length > 0 ) {
  171. // initialize all vertex normals in this triangle
  172. const tri = queue.pop().tri;
  173. const vertices = tri.vertices;
  174. const vertNormals = tri.normals;
  175. const faceNormal = tri.faceNormal; // Check if any edge is connected to another triangle edge
  176. const vertCount = vertices.length;
  177. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  178. const index = i2;
  179. const next = ( i2 + 1 ) % vertCount;
  180. const v0 = vertices[ index ];
  181. const v1 = vertices[ next ]; // delete this triangle from the list so it won't be found again
  182. const hash = hashEdge( v0, v1 );
  183. delete halfEdgeList[ hash ];
  184. const reverseHash = hashEdge( v1, v0 );
  185. const otherInfo = halfEdgeList[ reverseHash ];
  186. if ( otherInfo ) {
  187. const otherTri = otherInfo.tri;
  188. const otherIndex = otherInfo.index;
  189. const otherNormals = otherTri.normals;
  190. const otherVertCount = otherNormals.length;
  191. const otherFaceNormal = otherTri.faceNormal; // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  192. // hard edge. There are some cases where the line segments do not line up exactly
  193. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  194. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  195. continue;
  196. } // if this triangle has already been traversed then it won't be in
  197. // the halfEdgeList. If it has not then add it to the queue and delete
  198. // it so it won't be found again.
  199. if ( reverseHash in halfEdgeList ) {
  200. queue.push( otherInfo );
  201. delete halfEdgeList[ reverseHash ];
  202. } // share the first normal
  203. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  204. if ( vertNormals[ index ] && otherNormals[ otherNext ] && vertNormals[ index ] !== otherNormals[ otherNext ] ) {
  205. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  206. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  207. }
  208. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  209. if ( sharedNormal1 === null ) {
  210. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  211. // both edges already have different normals defined and shared. To work around this we create
  212. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  213. sharedNormal1 = {
  214. norm: new THREE.Vector3()
  215. };
  216. normals.push( sharedNormal1.norm );
  217. }
  218. if ( vertNormals[ index ] === null ) {
  219. vertNormals[ index ] = sharedNormal1;
  220. sharedNormal1.norm.add( faceNormal );
  221. }
  222. if ( otherNormals[ otherNext ] === null ) {
  223. otherNormals[ otherNext ] = sharedNormal1;
  224. sharedNormal1.norm.add( otherFaceNormal );
  225. } // share the second normal
  226. if ( vertNormals[ next ] && otherNormals[ otherIndex ] && vertNormals[ next ] !== otherNormals[ otherIndex ] ) {
  227. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  228. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  229. }
  230. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  231. if ( sharedNormal2 === null ) {
  232. sharedNormal2 = {
  233. norm: new THREE.Vector3()
  234. };
  235. normals.push( sharedNormal2.norm );
  236. }
  237. if ( vertNormals[ next ] === null ) {
  238. vertNormals[ next ] = sharedNormal2;
  239. sharedNormal2.norm.add( faceNormal );
  240. }
  241. if ( otherNormals[ otherIndex ] === null ) {
  242. otherNormals[ otherIndex ] = sharedNormal2;
  243. sharedNormal2.norm.add( otherFaceNormal );
  244. }
  245. }
  246. }
  247. }
  248. } // The normals of each face have been added up so now we average them by normalizing the vector.
  249. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  250. normals[ i ].normalize();
  251. }
  252. }
  253. function isPartType( type ) {
  254. return type === 'Part';
  255. }
  256. function isModelType( type ) {
  257. return type === 'Model' || type === 'Unofficial_Model';
  258. }
  259. function isPrimitiveType( type ) {
  260. return /primitive/i.test( type ) || type === 'Subpart';
  261. }
  262. class LineParser {
  263. constructor( line, lineNumber ) {
  264. this.line = line;
  265. this.lineLength = line.length;
  266. this.currentCharIndex = 0;
  267. this.currentChar = ' ';
  268. this.lineNumber = lineNumber;
  269. }
  270. seekNonSpace() {
  271. while ( this.currentCharIndex < this.lineLength ) {
  272. this.currentChar = this.line.charAt( this.currentCharIndex );
  273. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  274. return;
  275. }
  276. this.currentCharIndex ++;
  277. }
  278. }
  279. getToken() {
  280. const pos0 = this.currentCharIndex ++; // Seek space
  281. while ( this.currentCharIndex < this.lineLength ) {
  282. this.currentChar = this.line.charAt( this.currentCharIndex );
  283. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  284. break;
  285. }
  286. this.currentCharIndex ++;
  287. }
  288. const pos1 = this.currentCharIndex;
  289. this.seekNonSpace();
  290. return this.line.substring( pos0, pos1 );
  291. }
  292. getRemainingString() {
  293. return this.line.substring( this.currentCharIndex, this.lineLength );
  294. }
  295. isAtTheEnd() {
  296. return this.currentCharIndex >= this.lineLength;
  297. }
  298. setToEnd() {
  299. this.currentCharIndex = this.lineLength;
  300. }
  301. getLineNumberString() {
  302. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  303. }
  304. }
  305. class LDrawFileCache {
  306. constructor( loader ) {
  307. this.cache = {};
  308. this.loader = loader;
  309. }
  310. setData( key, contents ) {
  311. this.cache[ key.toLowerCase() ] = contents;
  312. }
  313. async loadData( fileName ) {
  314. const key = fileName.toLowerCase();
  315. if ( key in this.cache ) {
  316. return this.cache[ key ];
  317. }
  318. this.cache[ fileName ] = new Promise( async ( resolve, reject ) => {
  319. let triedLowerCase = false;
  320. let locationState = FILE_LOCATION_AS_IS;
  321. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  322. let subobjectURL = fileName;
  323. switch ( locationState ) {
  324. case FILE_LOCATION_AS_IS:
  325. locationState = locationState + 1;
  326. break;
  327. case FILE_LOCATION_TRY_PARTS:
  328. subobjectURL = 'parts/' + subobjectURL;
  329. locationState = locationState + 1;
  330. break;
  331. case FILE_LOCATION_TRY_P:
  332. subobjectURL = 'p/' + subobjectURL;
  333. locationState = locationState + 1;
  334. break;
  335. case FILE_LOCATION_TRY_MODELS:
  336. subobjectURL = 'models/' + subobjectURL;
  337. locationState = locationState + 1;
  338. break;
  339. case FILE_LOCATION_TRY_RELATIVE:
  340. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  341. locationState = locationState + 1;
  342. break;
  343. case FILE_LOCATION_TRY_ABSOLUTE:
  344. if ( triedLowerCase ) {
  345. // Try absolute path
  346. locationState = FILE_LOCATION_NOT_FOUND;
  347. } else {
  348. // Next attempt is lower case
  349. fileName = fileName.toLowerCase();
  350. subobjectURL = fileName;
  351. triedLowerCase = true;
  352. locationState = FILE_LOCATION_AS_IS;
  353. }
  354. break;
  355. }
  356. const loader = this.loader;
  357. const fileLoader = new THREE.FileLoader( loader.manager );
  358. fileLoader.setPath( loader.partsLibraryPath );
  359. fileLoader.setRequestHeader( loader.requestHeader );
  360. fileLoader.setWithCredentials( loader.withCredentials );
  361. try {
  362. const text = await fileLoader.loadAsync( subobjectURL );
  363. this.setData( fileName, text );
  364. resolve( text );
  365. return;
  366. } catch {
  367. continue;
  368. }
  369. }
  370. reject();
  371. } );
  372. return this.cache[ fileName ];
  373. }
  374. }
  375. function sortByMaterial( a, b ) {
  376. if ( a.colourCode === b.colourCode ) {
  377. return 0;
  378. }
  379. if ( a.colourCode < b.colourCode ) {
  380. return - 1;
  381. }
  382. return 1;
  383. }
  384. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  385. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  386. // With per face / segment material, implemented with mesh groups and materials array
  387. // Sort the faces or line segments by colour code to make later the mesh groups
  388. elements.sort( sortByMaterial );
  389. if ( totalElements === null ) {
  390. totalElements = elements.length;
  391. }
  392. const positions = new Float32Array( elementSize * totalElements * 3 );
  393. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  394. const materials = [];
  395. const quadArray = new Array( 6 );
  396. const bufferGeometry = new THREE.BufferGeometry();
  397. let prevMaterial = null;
  398. let index0 = 0;
  399. let numGroupVerts = 0;
  400. let offset = 0;
  401. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  402. const elem = elements[ iElem ];
  403. let vertices = elem.vertices;
  404. if ( vertices.length === 4 ) {
  405. quadArray[ 0 ] = vertices[ 0 ];
  406. quadArray[ 1 ] = vertices[ 1 ];
  407. quadArray[ 2 ] = vertices[ 2 ];
  408. quadArray[ 3 ] = vertices[ 0 ];
  409. quadArray[ 4 ] = vertices[ 2 ];
  410. quadArray[ 5 ] = vertices[ 3 ];
  411. vertices = quadArray;
  412. }
  413. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  414. const v = vertices[ j ];
  415. const index = offset + j * 3;
  416. positions[ index + 0 ] = v.x;
  417. positions[ index + 1 ] = v.y;
  418. positions[ index + 2 ] = v.z;
  419. }
  420. if ( elementSize === 3 ) {
  421. let elemNormals = elem.normals;
  422. if ( elemNormals.length === 4 ) {
  423. quadArray[ 0 ] = elemNormals[ 0 ];
  424. quadArray[ 1 ] = elemNormals[ 1 ];
  425. quadArray[ 2 ] = elemNormals[ 2 ];
  426. quadArray[ 3 ] = elemNormals[ 0 ];
  427. quadArray[ 4 ] = elemNormals[ 2 ];
  428. quadArray[ 5 ] = elemNormals[ 3 ];
  429. elemNormals = quadArray;
  430. }
  431. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  432. let n = elem.faceNormal;
  433. if ( elemNormals[ j ] ) {
  434. n = elemNormals[ j ].norm;
  435. }
  436. const index = offset + j * 3;
  437. normals[ index + 0 ] = n.x;
  438. normals[ index + 1 ] = n.y;
  439. normals[ index + 2 ] = n.z;
  440. }
  441. }
  442. if ( prevMaterial !== elem.material ) {
  443. if ( prevMaterial !== null ) {
  444. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  445. }
  446. materials.push( elem.material );
  447. prevMaterial = elem.material;
  448. index0 = offset / 3;
  449. numGroupVerts = vertices.length;
  450. } else {
  451. numGroupVerts += vertices.length;
  452. }
  453. offset += 3 * vertices.length;
  454. }
  455. if ( numGroupVerts > 0 ) {
  456. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  457. }
  458. bufferGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  459. if ( normals !== null ) {
  460. bufferGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  461. }
  462. let object3d = null;
  463. if ( elementSize === 2 ) {
  464. object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  465. } else if ( elementSize === 3 ) {
  466. object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  467. }
  468. if ( isConditionalSegments ) {
  469. object3d.isConditionalLine = true;
  470. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  471. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  472. const directionArray = new Float32Array( elements.length * 3 * 2 );
  473. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  474. const os = elements[ i ];
  475. const vertices = os.vertices;
  476. const controlPoints = os.controlPoints;
  477. const c0 = controlPoints[ 0 ];
  478. const c1 = controlPoints[ 1 ];
  479. const v0 = vertices[ 0 ];
  480. const v1 = vertices[ 1 ];
  481. const index = i * 3 * 2;
  482. controlArray0[ index + 0 ] = c0.x;
  483. controlArray0[ index + 1 ] = c0.y;
  484. controlArray0[ index + 2 ] = c0.z;
  485. controlArray0[ index + 3 ] = c0.x;
  486. controlArray0[ index + 4 ] = c0.y;
  487. controlArray0[ index + 5 ] = c0.z;
  488. controlArray1[ index + 0 ] = c1.x;
  489. controlArray1[ index + 1 ] = c1.y;
  490. controlArray1[ index + 2 ] = c1.z;
  491. controlArray1[ index + 3 ] = c1.x;
  492. controlArray1[ index + 4 ] = c1.y;
  493. controlArray1[ index + 5 ] = c1.z;
  494. directionArray[ index + 0 ] = v1.x - v0.x;
  495. directionArray[ index + 1 ] = v1.y - v0.y;
  496. directionArray[ index + 2 ] = v1.z - v0.z;
  497. directionArray[ index + 3 ] = v1.x - v0.x;
  498. directionArray[ index + 4 ] = v1.y - v0.y;
  499. directionArray[ index + 5 ] = v1.z - v0.z;
  500. }
  501. bufferGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  502. bufferGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  503. bufferGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  504. }
  505. return object3d;
  506. } //
  507. class LDrawLoader extends THREE.Loader {
  508. constructor( manager ) {
  509. super( manager ); // Array of THREE.Material
  510. this.materials = []; // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  511. // This also allows to handle the embedded text files ("0 FILE" lines)
  512. this.cache = new LDrawFileCache( 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.
  513. this.fileMap = null;
  514. this.rootParseScope = this.newParseScopeLevel(); // Add default main triangle and line edge materials (used in pieces that can be coloured with a main color)
  515. this.setMaterials( [ this.parseColourMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ), this.parseColourMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) ] ); // If this flag is set to true, each subobject will be a Object.
  516. // If not (the default), only one object which contains all the merged primitives will be created.
  517. this.separateObjects = false; // If this flag is set to true the vertex normals will be smoothed.
  518. this.smoothNormals = true; // The path to load parts from the LDraw parts library from.
  519. this.partsLibraryPath = '';
  520. }
  521. setPartsLibraryPath( path ) {
  522. this.partsLibraryPath = path;
  523. return this;
  524. }
  525. async preloadMaterials( url ) {
  526. const fileLoader = new THREE.FileLoader( this.manager );
  527. fileLoader.setPath( this.path );
  528. fileLoader.setRequestHeader( this.requestHeader );
  529. fileLoader.setWithCredentials( this.withCredentials );
  530. const text = await fileLoader.loadAsync( url );
  531. const colorLineRegex = /^0 !COLOUR/;
  532. const lines = text.split( /[\n\r]/g );
  533. const materials = [];
  534. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  535. const line = lines[ i ];
  536. if ( colorLineRegex.test( line ) ) {
  537. const directive = line.replace( colorLineRegex, '' );
  538. const material = this.parseColourMetaDirective( new LineParser( directive ) );
  539. materials.push( material );
  540. }
  541. }
  542. this.setMaterials( materials );
  543. }
  544. load( url, onLoad, onProgress, onError ) {
  545. if ( ! this.fileMap ) {
  546. this.fileMap = {};
  547. }
  548. const fileLoader = new THREE.FileLoader( this.manager );
  549. fileLoader.setPath( this.path );
  550. fileLoader.setRequestHeader( this.requestHeader );
  551. fileLoader.setWithCredentials( this.withCredentials );
  552. fileLoader.load( url, text => {
  553. this.processObject( text, null, url, this.rootParseScope ).then( function ( result ) {
  554. onLoad( result.groupObject );
  555. } );
  556. }, onProgress, onError );
  557. }
  558. parse( text, path, onLoad ) {
  559. // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
  560. this.processObject( text, null, path, this.rootParseScope ).then( function ( result ) {
  561. onLoad( result.groupObject );
  562. } );
  563. }
  564. setMaterials( materials ) {
  565. // Clears parse scopes stack, adds new scope with material library
  566. this.rootParseScope = this.newParseScopeLevel( materials );
  567. this.rootParseScope.isFromParse = false;
  568. this.materials = materials;
  569. return this;
  570. }
  571. setFileMap( fileMap ) {
  572. this.fileMap = fileMap;
  573. return this;
  574. }
  575. newParseScopeLevel( materials = null, parentScope = null ) {
  576. // Adds a new scope level, assign materials to it and returns it
  577. const matLib = {};
  578. if ( materials ) {
  579. for ( let i = 0, n = materials.length; i < n; i ++ ) {
  580. const material = materials[ i ];
  581. matLib[ material.userData.code ] = material;
  582. }
  583. }
  584. const newParseScope = {
  585. parentScope: parentScope,
  586. lib: matLib,
  587. url: null,
  588. // Subobjects
  589. subobjects: null,
  590. numSubobjects: 0,
  591. subobjectIndex: 0,
  592. inverted: false,
  593. category: null,
  594. keywords: null,
  595. // Current subobject
  596. currentFileName: null,
  597. mainColourCode: parentScope ? parentScope.mainColourCode : '16',
  598. mainEdgeColourCode: parentScope ? parentScope.mainEdgeColourCode : '24',
  599. currentMatrix: new THREE.Matrix4(),
  600. matrix: new THREE.Matrix4(),
  601. // If false, it is a root material scope previous to parse
  602. isFromParse: true,
  603. faces: null,
  604. lineSegments: null,
  605. conditionalSegments: null,
  606. totalFaces: 0,
  607. // If true, this object is the start of a construction step
  608. startingConstructionStep: false
  609. };
  610. return newParseScope;
  611. }
  612. addMaterial( material, parseScope ) {
  613. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  614. const matLib = parseScope.lib;
  615. if ( ! matLib[ material.userData.code ] ) {
  616. this.materials.push( material );
  617. }
  618. matLib[ material.userData.code ] = material;
  619. return this;
  620. }
  621. getMaterial( colourCode, parseScope = this.rootParseScope ) {
  622. // Given a colour code search its material in the parse scopes stack
  623. if ( colourCode.startsWith( '0x2' ) ) {
  624. // Special 'direct' material value (RGB colour)
  625. const colour = colourCode.substring( 3 );
  626. return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
  627. }
  628. while ( parseScope ) {
  629. const material = parseScope.lib[ colourCode ];
  630. if ( material ) {
  631. return material;
  632. } else {
  633. parseScope = parseScope.parentScope;
  634. }
  635. } // Material was not found
  636. return null;
  637. }
  638. parseColourMetaDirective( lineParser ) {
  639. // Parses a colour definition and returns a THREE.Material
  640. let code = null; // Triangle and line colours
  641. let colour = 0xFF00FF;
  642. let edgeColour = 0xFF00FF; // Transparency
  643. let alpha = 1;
  644. let isTransparent = false; // Self-illumination:
  645. let luminance = 0;
  646. let finishType = FINISH_TYPE_DEFAULT;
  647. let edgeMaterial = null;
  648. const name = lineParser.getToken();
  649. if ( ! name ) {
  650. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.';
  651. } // Parse tag tokens and their parameters
  652. let token = null;
  653. while ( true ) {
  654. token = lineParser.getToken();
  655. if ( ! token ) {
  656. break;
  657. }
  658. switch ( token.toUpperCase() ) {
  659. case 'CODE':
  660. code = lineParser.getToken();
  661. break;
  662. case 'VALUE':
  663. colour = lineParser.getToken();
  664. if ( colour.startsWith( '0x' ) ) {
  665. colour = '#' + colour.substring( 2 );
  666. } else if ( ! colour.startsWith( '#' ) ) {
  667. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.';
  668. }
  669. break;
  670. case 'EDGE':
  671. edgeColour = lineParser.getToken();
  672. if ( edgeColour.startsWith( '0x' ) ) {
  673. edgeColour = '#' + edgeColour.substring( 2 );
  674. } else if ( ! edgeColour.startsWith( '#' ) ) {
  675. // Try to see if edge colour is a colour code
  676. edgeMaterial = this.getMaterial( edgeColour );
  677. if ( ! edgeMaterial ) {
  678. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.';
  679. } // Get the edge material for this triangle material
  680. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  681. }
  682. break;
  683. case 'ALPHA':
  684. alpha = parseInt( lineParser.getToken() );
  685. if ( isNaN( alpha ) ) {
  686. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.';
  687. }
  688. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  689. if ( alpha < 1 ) {
  690. isTransparent = true;
  691. }
  692. break;
  693. case 'LUMINANCE':
  694. luminance = parseInt( lineParser.getToken() );
  695. if ( isNaN( luminance ) ) {
  696. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.';
  697. }
  698. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  699. break;
  700. case 'CHROME':
  701. finishType = FINISH_TYPE_CHROME;
  702. break;
  703. case 'PEARLESCENT':
  704. finishType = FINISH_TYPE_PEARLESCENT;
  705. break;
  706. case 'RUBBER':
  707. finishType = FINISH_TYPE_RUBBER;
  708. break;
  709. case 'MATTE_METALLIC':
  710. finishType = FINISH_TYPE_MATTE_METALLIC;
  711. break;
  712. case 'METAL':
  713. finishType = FINISH_TYPE_METAL;
  714. break;
  715. case 'MATERIAL':
  716. // Not implemented
  717. lineParser.setToEnd();
  718. break;
  719. default:
  720. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.';
  721. break;
  722. }
  723. }
  724. let material = null;
  725. switch ( finishType ) {
  726. case FINISH_TYPE_DEFAULT:
  727. material = new THREE.MeshStandardMaterial( {
  728. color: colour,
  729. roughness: 0.3,
  730. metalness: 0
  731. } );
  732. break;
  733. case FINISH_TYPE_PEARLESCENT:
  734. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  735. const specular = new THREE.Color( colour );
  736. const hsl = specular.getHSL( {
  737. h: 0,
  738. s: 0,
  739. l: 0
  740. } );
  741. hsl.h = ( hsl.h + 0.5 ) % 1;
  742. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  743. specular.setHSL( hsl.h, hsl.s, hsl.l );
  744. material = new THREE.MeshPhongMaterial( {
  745. color: colour,
  746. specular: specular,
  747. shininess: 10,
  748. reflectivity: 0.3
  749. } );
  750. break;
  751. case FINISH_TYPE_CHROME:
  752. // Mirror finish surface
  753. material = new THREE.MeshStandardMaterial( {
  754. color: colour,
  755. roughness: 0,
  756. metalness: 1
  757. } );
  758. break;
  759. case FINISH_TYPE_RUBBER:
  760. // Rubber finish
  761. material = new THREE.MeshStandardMaterial( {
  762. color: colour,
  763. roughness: 0.9,
  764. metalness: 0
  765. } );
  766. break;
  767. case FINISH_TYPE_MATTE_METALLIC:
  768. // Brushed metal finish
  769. material = new THREE.MeshStandardMaterial( {
  770. color: colour,
  771. roughness: 0.8,
  772. metalness: 0.4
  773. } );
  774. break;
  775. case FINISH_TYPE_METAL:
  776. // Average metal finish
  777. material = new THREE.MeshStandardMaterial( {
  778. color: colour,
  779. roughness: 0.2,
  780. metalness: 0.85
  781. } );
  782. break;
  783. default:
  784. // Should not happen
  785. break;
  786. }
  787. material.transparent = isTransparent;
  788. material.premultipliedAlpha = true;
  789. material.opacity = alpha;
  790. material.depthWrite = ! isTransparent;
  791. material.polygonOffset = true;
  792. material.polygonOffsetFactor = 1;
  793. if ( luminance !== 0 ) {
  794. material.emissive.set( material.color ).multiplyScalar( luminance );
  795. }
  796. if ( ! edgeMaterial ) {
  797. // This is the material used for edges
  798. edgeMaterial = new THREE.LineBasicMaterial( {
  799. color: edgeColour,
  800. transparent: isTransparent,
  801. opacity: alpha,
  802. depthWrite: ! isTransparent
  803. } );
  804. edgeMaterial.userData.code = code;
  805. edgeMaterial.name = name + ' - Edge'; // This is the material used for conditional edges
  806. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  807. fog: true,
  808. transparent: isTransparent,
  809. depthWrite: ! isTransparent,
  810. color: edgeColour,
  811. opacity: alpha
  812. } );
  813. }
  814. material.userData.code = code;
  815. material.name = name;
  816. material.userData.edgeMaterial = edgeMaterial;
  817. return material;
  818. } //
  819. objectParse( text, parseScope ) {
  820. // Retrieve data from the parent parse scope
  821. const currentParseScope = parseScope;
  822. const parentParseScope = currentParseScope.parentScope; // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  823. const mainColourCode = currentParseScope.mainColourCode;
  824. const mainEdgeColourCode = currentParseScope.mainEdgeColourCode; // Parse result variables
  825. let faces;
  826. let lineSegments;
  827. let conditionalSegments;
  828. const subobjects = [];
  829. let category = null;
  830. let keywords = null;
  831. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  832. // This is faster than String.split with regex that splits on both
  833. text = text.replace( /\r\n/g, '\n' );
  834. }
  835. const lines = text.split( '\n' );
  836. const numLines = lines.length;
  837. let parsingEmbeddedFiles = false;
  838. let currentEmbeddedFileName = null;
  839. let currentEmbeddedText = null;
  840. let bfcCertified = false;
  841. let bfcCCW = true;
  842. let bfcInverted = false;
  843. let bfcCull = true;
  844. let type = '';
  845. let startingConstructionStep = false;
  846. const scope = this;
  847. function parseColourCode( lineParser, forEdge ) {
  848. // Parses next colour code and returns a THREE.Material
  849. let colourCode = lineParser.getToken();
  850. if ( ! forEdge && colourCode === '16' ) {
  851. colourCode = mainColourCode;
  852. }
  853. if ( forEdge && colourCode === '24' ) {
  854. colourCode = mainEdgeColourCode;
  855. }
  856. const material = scope.getMaterial( colourCode, currentParseScope );
  857. if ( ! material ) {
  858. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  859. }
  860. return material;
  861. }
  862. function parseVector( lp ) {
  863. const v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  864. if ( ! scope.separateObjects ) {
  865. v.applyMatrix4( currentParseScope.currentMatrix );
  866. }
  867. return v;
  868. } // Parse all line commands
  869. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  870. const line = lines[ lineIndex ];
  871. if ( line.length === 0 ) continue;
  872. if ( parsingEmbeddedFiles ) {
  873. if ( line.startsWith( '0 FILE ' ) ) {
  874. // Save previous embedded file in the cache
  875. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText ); // New embedded text file
  876. currentEmbeddedFileName = line.substring( 7 );
  877. currentEmbeddedText = '';
  878. } else {
  879. currentEmbeddedText += line + '\n';
  880. }
  881. continue;
  882. }
  883. const lp = new LineParser( line, lineIndex + 1 );
  884. lp.seekNonSpace();
  885. if ( lp.isAtTheEnd() ) {
  886. // Empty line
  887. continue;
  888. } // Parse the line type
  889. const lineType = lp.getToken();
  890. let material;
  891. let segment;
  892. let inverted;
  893. let ccw;
  894. let doubleSided;
  895. let v0, v1, v2, v3, c0, c1, faceNormal;
  896. switch ( lineType ) {
  897. // Line type 0: Comment or META
  898. case '0':
  899. // Parse meta directive
  900. const meta = lp.getToken();
  901. if ( meta ) {
  902. switch ( meta ) {
  903. case '!LDRAW_ORG':
  904. type = lp.getToken();
  905. currentParseScope.faces = [];
  906. currentParseScope.lineSegments = [];
  907. currentParseScope.conditionalSegments = [];
  908. currentParseScope.type = type;
  909. const isRoot = ! parentParseScope.isFromParse;
  910. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  911. currentParseScope.groupObject = new THREE.Group();
  912. currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
  913. } // If the scale of the object is negated then the triangle winding order
  914. // needs to be flipped.
  915. if ( currentParseScope.matrix.determinant() < 0 && ( scope.separateObjects && isPrimitiveType( type ) || ! scope.separateObjects ) ) {
  916. currentParseScope.inverted = ! currentParseScope.inverted;
  917. }
  918. faces = currentParseScope.faces;
  919. lineSegments = currentParseScope.lineSegments;
  920. conditionalSegments = currentParseScope.conditionalSegments;
  921. break;
  922. case '!COLOUR':
  923. material = this.parseColourMetaDirective( lp );
  924. if ( material ) {
  925. this.addMaterial( material, parseScope );
  926. } else {
  927. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  928. }
  929. break;
  930. case '!CATEGORY':
  931. category = lp.getToken();
  932. break;
  933. case '!KEYWORDS':
  934. const newKeywords = lp.getRemainingString().split( ',' );
  935. if ( newKeywords.length > 0 ) {
  936. if ( ! keywords ) {
  937. keywords = [];
  938. }
  939. newKeywords.forEach( function ( keyword ) {
  940. keywords.push( keyword.trim() );
  941. } );
  942. }
  943. break;
  944. case 'FILE':
  945. if ( lineIndex > 0 ) {
  946. // Start embedded text files parsing
  947. parsingEmbeddedFiles = true;
  948. currentEmbeddedFileName = lp.getRemainingString();
  949. currentEmbeddedText = '';
  950. bfcCertified = false;
  951. bfcCCW = true;
  952. }
  953. break;
  954. case 'BFC':
  955. // Changes to the backface culling state
  956. while ( ! lp.isAtTheEnd() ) {
  957. const token = lp.getToken();
  958. switch ( token ) {
  959. case 'CERTIFY':
  960. case 'NOCERTIFY':
  961. bfcCertified = token === 'CERTIFY';
  962. bfcCCW = true;
  963. break;
  964. case 'CW':
  965. case 'CCW':
  966. bfcCCW = token === 'CCW';
  967. break;
  968. case 'INVERTNEXT':
  969. bfcInverted = true;
  970. break;
  971. case 'CLIP':
  972. case 'NOCLIP':
  973. bfcCull = token === 'CLIP';
  974. break;
  975. default:
  976. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  977. break;
  978. }
  979. }
  980. break;
  981. case 'STEP':
  982. startingConstructionStep = true;
  983. break;
  984. default:
  985. // Other meta directives are not implemented
  986. break;
  987. }
  988. }
  989. break;
  990. // Line type 1: Sub-object file
  991. case '1':
  992. material = parseColourCode( lp );
  993. const posX = parseFloat( lp.getToken() );
  994. const posY = parseFloat( lp.getToken() );
  995. const posZ = parseFloat( lp.getToken() );
  996. const m0 = parseFloat( lp.getToken() );
  997. const m1 = parseFloat( lp.getToken() );
  998. const m2 = parseFloat( lp.getToken() );
  999. const m3 = parseFloat( lp.getToken() );
  1000. const m4 = parseFloat( lp.getToken() );
  1001. const m5 = parseFloat( lp.getToken() );
  1002. const m6 = parseFloat( lp.getToken() );
  1003. const m7 = parseFloat( lp.getToken() );
  1004. const m8 = parseFloat( lp.getToken() );
  1005. const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
  1006. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  1007. if ( scope.fileMap[ fileName ] ) {
  1008. // Found the subobject path in the preloaded file path map
  1009. fileName = scope.fileMap[ fileName ];
  1010. } else {
  1011. // Standardized subfolders
  1012. if ( fileName.startsWith( 's/' ) ) {
  1013. fileName = 'parts/' + fileName;
  1014. } else if ( fileName.startsWith( '48/' ) ) {
  1015. fileName = 'p/' + fileName;
  1016. }
  1017. }
  1018. subobjects.push( {
  1019. material: material,
  1020. matrix: matrix,
  1021. fileName: fileName,
  1022. inverted: bfcInverted !== currentParseScope.inverted,
  1023. startingConstructionStep: startingConstructionStep
  1024. } );
  1025. bfcInverted = false;
  1026. break;
  1027. // Line type 2: Line segment
  1028. case '2':
  1029. material = parseColourCode( lp, true );
  1030. v0 = parseVector( lp );
  1031. v1 = parseVector( lp );
  1032. segment = {
  1033. material: material.userData.edgeMaterial,
  1034. colourCode: material.userData.code,
  1035. v0: v0,
  1036. v1: v1,
  1037. vertices: [ v0, v1 ]
  1038. };
  1039. lineSegments.push( segment );
  1040. break;
  1041. // Line type 5: Conditional Line segment
  1042. case '5':
  1043. material = parseColourCode( lp, true );
  1044. v0 = parseVector( lp );
  1045. v1 = parseVector( lp );
  1046. c0 = parseVector( lp );
  1047. c1 = parseVector( lp );
  1048. segment = {
  1049. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  1050. colourCode: material.userData.code,
  1051. vertices: [ v0, v1 ],
  1052. controlPoints: [ c0, c1 ]
  1053. };
  1054. conditionalSegments.push( segment );
  1055. break;
  1056. // Line type 3: Triangle
  1057. case '3':
  1058. material = parseColourCode( lp );
  1059. inverted = currentParseScope.inverted;
  1060. ccw = bfcCCW !== inverted;
  1061. doubleSided = ! bfcCertified || ! bfcCull;
  1062. if ( ccw === true ) {
  1063. v0 = parseVector( lp );
  1064. v1 = parseVector( lp );
  1065. v2 = parseVector( lp );
  1066. } else {
  1067. v2 = parseVector( lp );
  1068. v1 = parseVector( lp );
  1069. v0 = parseVector( lp );
  1070. }
  1071. _tempVec0.subVectors( v1, v0 );
  1072. _tempVec1.subVectors( v2, v1 );
  1073. faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  1074. faces.push( {
  1075. material: material,
  1076. colourCode: material.userData.code,
  1077. faceNormal: faceNormal,
  1078. vertices: [ v0, v1, v2 ],
  1079. normals: [ null, null, null ]
  1080. } );
  1081. currentParseScope.totalFaces ++;
  1082. if ( doubleSided === true ) {
  1083. faces.push( {
  1084. material: material,
  1085. colourCode: material.userData.code,
  1086. faceNormal: faceNormal,
  1087. vertices: [ v2, v1, v0 ],
  1088. normals: [ null, null, null ]
  1089. } );
  1090. currentParseScope.totalFaces ++;
  1091. }
  1092. break;
  1093. // Line type 4: Quadrilateral
  1094. case '4':
  1095. material = parseColourCode( lp );
  1096. inverted = currentParseScope.inverted;
  1097. ccw = bfcCCW !== inverted;
  1098. doubleSided = ! bfcCertified || ! bfcCull;
  1099. if ( ccw === true ) {
  1100. v0 = parseVector( lp );
  1101. v1 = parseVector( lp );
  1102. v2 = parseVector( lp );
  1103. v3 = parseVector( lp );
  1104. } else {
  1105. v3 = parseVector( lp );
  1106. v2 = parseVector( lp );
  1107. v1 = parseVector( lp );
  1108. v0 = parseVector( lp );
  1109. }
  1110. _tempVec0.subVectors( v1, v0 );
  1111. _tempVec1.subVectors( v2, v1 );
  1112. faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize(); // specifically place the triangle diagonal in the v0 and v1 slots so we can
  1113. // account for the doubling of vertices later when smoothing normals.
  1114. faces.push( {
  1115. material: material,
  1116. colourCode: material.userData.code,
  1117. faceNormal: faceNormal,
  1118. vertices: [ v0, v1, v2, v3 ],
  1119. normals: [ null, null, null, null ]
  1120. } );
  1121. currentParseScope.totalFaces += 2;
  1122. if ( doubleSided === true ) {
  1123. faces.push( {
  1124. material: material,
  1125. colourCode: material.userData.code,
  1126. faceNormal: faceNormal,
  1127. vertices: [ v3, v2, v1, v0 ],
  1128. normals: [ null, null, null, null ]
  1129. } );
  1130. currentParseScope.totalFaces += 2;
  1131. }
  1132. break;
  1133. default:
  1134. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1135. break;
  1136. }
  1137. }
  1138. if ( parsingEmbeddedFiles ) {
  1139. this.cache.setData( currentEmbeddedFileName.toLowerCase(), currentEmbeddedText );
  1140. }
  1141. currentParseScope.category = category;
  1142. currentParseScope.keywords = keywords;
  1143. currentParseScope.subobjects = subobjects;
  1144. currentParseScope.numSubobjects = subobjects.length;
  1145. currentParseScope.subobjectIndex = 0;
  1146. }
  1147. computeConstructionSteps( model ) {
  1148. // Sets userdata.constructionStep number in THREE.Group objects and userData.numConstructionSteps number in the root THREE.Group object.
  1149. let stepNumber = 0;
  1150. model.traverse( c => {
  1151. if ( c.isGroup ) {
  1152. if ( c.userData.startingConstructionStep ) {
  1153. stepNumber ++;
  1154. }
  1155. c.userData.constructionStep = stepNumber;
  1156. }
  1157. } );
  1158. model.userData.numConstructionSteps = stepNumber + 1;
  1159. }
  1160. finalizeObject( subobjectParseScope ) {
  1161. const parentParseScope = subobjectParseScope.parentScope; // Smooth the normals if this is a part or if this is a case where the subpart
  1162. // is added directly into the parent model (meaning it will never get smoothed by
  1163. // being added to a part)
  1164. const doSmooth = isPartType( subobjectParseScope.type ) || ! isPartType( subobjectParseScope.type ) && ! isModelType( subobjectParseScope.type ) && isModelType( subobjectParseScope.parentScope.type );
  1165. if ( this.smoothNormals && doSmooth ) {
  1166. smoothNormals( subobjectParseScope.faces, subobjectParseScope.lineSegments );
  1167. }
  1168. const isRoot = ! parentParseScope.isFromParse;
  1169. if ( this.separateObjects && ! isPrimitiveType( subobjectParseScope.type ) || isRoot ) {
  1170. const objGroup = subobjectParseScope.groupObject;
  1171. if ( subobjectParseScope.faces.length > 0 ) {
  1172. objGroup.add( createObject( subobjectParseScope.faces, 3, false, subobjectParseScope.totalFaces ) );
  1173. }
  1174. if ( subobjectParseScope.lineSegments.length > 0 ) {
  1175. objGroup.add( createObject( subobjectParseScope.lineSegments, 2 ) );
  1176. }
  1177. if ( subobjectParseScope.conditionalSegments.length > 0 ) {
  1178. objGroup.add( createObject( subobjectParseScope.conditionalSegments, 2, true ) );
  1179. }
  1180. if ( parentParseScope.groupObject ) {
  1181. objGroup.name = subobjectParseScope.fileName;
  1182. objGroup.userData.category = subobjectParseScope.category;
  1183. objGroup.userData.keywords = subobjectParseScope.keywords;
  1184. subobjectParseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  1185. parentParseScope.groupObject.add( objGroup );
  1186. }
  1187. } else {
  1188. const separateObjects = this.separateObjects;
  1189. const parentLineSegments = parentParseScope.lineSegments;
  1190. const parentConditionalSegments = parentParseScope.conditionalSegments;
  1191. const parentFaces = parentParseScope.faces;
  1192. const lineSegments = subobjectParseScope.lineSegments;
  1193. const conditionalSegments = subobjectParseScope.conditionalSegments;
  1194. const faces = subobjectParseScope.faces;
  1195. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  1196. const ls = lineSegments[ i ];
  1197. if ( separateObjects ) {
  1198. const vertices = ls.vertices;
  1199. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1200. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1201. }
  1202. parentLineSegments.push( ls );
  1203. }
  1204. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  1205. const os = conditionalSegments[ i ];
  1206. if ( separateObjects ) {
  1207. const vertices = os.vertices;
  1208. const controlPoints = os.controlPoints;
  1209. vertices[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1210. vertices[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1211. controlPoints[ 0 ].applyMatrix4( subobjectParseScope.matrix );
  1212. controlPoints[ 1 ].applyMatrix4( subobjectParseScope.matrix );
  1213. }
  1214. parentConditionalSegments.push( os );
  1215. }
  1216. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  1217. const tri = faces[ i ];
  1218. if ( separateObjects ) {
  1219. const vertices = tri.vertices;
  1220. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  1221. vertices[ i ] = vertices[ i ].clone().applyMatrix4( subobjectParseScope.matrix );
  1222. }
  1223. _tempVec0.subVectors( vertices[ 1 ], vertices[ 0 ] );
  1224. _tempVec1.subVectors( vertices[ 2 ], vertices[ 1 ] );
  1225. tri.faceNormal.crossVectors( _tempVec0, _tempVec1 ).normalize();
  1226. }
  1227. parentFaces.push( tri );
  1228. }
  1229. parentParseScope.totalFaces += subobjectParseScope.totalFaces;
  1230. }
  1231. }
  1232. async processObject( text, subobject, url, parentScope ) {
  1233. const scope = this;
  1234. const parseScope = this.newParseScopeLevel( null, parentScope );
  1235. parseScope.url = url;
  1236. const parentParseScope = parseScope.parentScope; // Set current matrix
  1237. if ( subobject ) {
  1238. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  1239. parseScope.matrix.copy( subobject.matrix );
  1240. parseScope.inverted = subobject.inverted;
  1241. parseScope.startingConstructionStep = subobject.startingConstructionStep;
  1242. parseScope.mainColourCode = subobject.material.userData.code;
  1243. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  1244. parseScope.fileName = subobject.fileName;
  1245. } // Parse the object
  1246. this.objectParse( text, parseScope );
  1247. const subobjects = parseScope.subobjects;
  1248. const promises = [];
  1249. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  1250. promises.push( loadSubobject( parseScope.subobjects[ i ] ) );
  1251. } // Kick off of the downloads in parallel but process all the subobjects
  1252. // in order so all the assembly instructions are correct
  1253. const subobjectScopes = await Promise.all( promises );
  1254. for ( let i = 0, l = subobjectScopes.length; i < l; i ++ ) {
  1255. this.finalizeObject( subobjectScopes[ i ] );
  1256. } // If it is root object then finalize this object and compute construction steps
  1257. if ( ! parentParseScope.isFromParse ) {
  1258. this.finalizeObject( parseScope );
  1259. this.computeConstructionSteps( parseScope.groupObject );
  1260. }
  1261. return parseScope;
  1262. function loadSubobject( subobject ) {
  1263. return scope.cache.loadData( subobject.fileName ).then( function ( text ) {
  1264. return scope.processObject( text, subobject, url, parseScope );
  1265. } ).catch( function () {
  1266. console.warn( 'LDrawLoader: Subobject "' + subobject.fileName + '" could not be found.' );
  1267. } );
  1268. }
  1269. }
  1270. }
  1271. THREE.LDrawLoader = LDrawLoader;
  1272. } )();