LDrawLoader.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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 isPrimitiveType( type ) {
  254. return /primitive/i.test( type ) || type === 'Subpart';
  255. }
  256. class LineParser {
  257. constructor( line, lineNumber ) {
  258. this.line = line;
  259. this.lineLength = line.length;
  260. this.currentCharIndex = 0;
  261. this.currentChar = ' ';
  262. this.lineNumber = lineNumber;
  263. }
  264. seekNonSpace() {
  265. while ( this.currentCharIndex < this.lineLength ) {
  266. this.currentChar = this.line.charAt( this.currentCharIndex );
  267. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  268. return;
  269. }
  270. this.currentCharIndex ++;
  271. }
  272. }
  273. getToken() {
  274. const pos0 = this.currentCharIndex ++; // Seek space
  275. while ( this.currentCharIndex < this.lineLength ) {
  276. this.currentChar = this.line.charAt( this.currentCharIndex );
  277. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  278. break;
  279. }
  280. this.currentCharIndex ++;
  281. }
  282. const pos1 = this.currentCharIndex;
  283. this.seekNonSpace();
  284. return this.line.substring( pos0, pos1 );
  285. }
  286. getRemainingString() {
  287. return this.line.substring( this.currentCharIndex, this.lineLength );
  288. }
  289. isAtTheEnd() {
  290. return this.currentCharIndex >= this.lineLength;
  291. }
  292. setToEnd() {
  293. this.currentCharIndex = this.lineLength;
  294. }
  295. getLineNumberString() {
  296. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  297. }
  298. }
  299. function sortByMaterial( a, b ) {
  300. if ( a.colourCode === b.colourCode ) {
  301. return 0;
  302. }
  303. if ( a.colourCode < b.colourCode ) {
  304. return - 1;
  305. }
  306. return 1;
  307. }
  308. function createObject( elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  309. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  310. // With per face / segment material, implemented with mesh groups and materials array
  311. // Sort the faces or line segments by colour code to make later the mesh groups
  312. elements.sort( sortByMaterial );
  313. if ( totalElements === null ) {
  314. totalElements = elements.length;
  315. }
  316. const positions = new Float32Array( elementSize * totalElements * 3 );
  317. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  318. const materials = [];
  319. const quadArray = new Array( 6 );
  320. const bufferGeometry = new THREE.BufferGeometry();
  321. let prevMaterial = null;
  322. let index0 = 0;
  323. let numGroupVerts = 0;
  324. let offset = 0;
  325. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  326. const elem = elements[ iElem ];
  327. let vertices = elem.vertices;
  328. if ( vertices.length === 4 ) {
  329. quadArray[ 0 ] = vertices[ 0 ];
  330. quadArray[ 1 ] = vertices[ 1 ];
  331. quadArray[ 2 ] = vertices[ 2 ];
  332. quadArray[ 3 ] = vertices[ 0 ];
  333. quadArray[ 4 ] = vertices[ 2 ];
  334. quadArray[ 5 ] = vertices[ 3 ];
  335. vertices = quadArray;
  336. }
  337. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  338. const v = vertices[ j ];
  339. const index = offset + j * 3;
  340. positions[ index + 0 ] = v.x;
  341. positions[ index + 1 ] = v.y;
  342. positions[ index + 2 ] = v.z;
  343. }
  344. if ( elementSize === 3 ) {
  345. let elemNormals = elem.normals;
  346. if ( elemNormals.length === 4 ) {
  347. quadArray[ 0 ] = elemNormals[ 0 ];
  348. quadArray[ 1 ] = elemNormals[ 1 ];
  349. quadArray[ 2 ] = elemNormals[ 2 ];
  350. quadArray[ 3 ] = elemNormals[ 0 ];
  351. quadArray[ 4 ] = elemNormals[ 2 ];
  352. quadArray[ 5 ] = elemNormals[ 3 ];
  353. elemNormals = quadArray;
  354. }
  355. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  356. let n = elem.faceNormal;
  357. if ( elemNormals[ j ] ) {
  358. n = elemNormals[ j ].norm;
  359. }
  360. const index = offset + j * 3;
  361. normals[ index + 0 ] = n.x;
  362. normals[ index + 1 ] = n.y;
  363. normals[ index + 2 ] = n.z;
  364. }
  365. }
  366. if ( prevMaterial !== elem.material ) {
  367. if ( prevMaterial !== null ) {
  368. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  369. }
  370. materials.push( elem.material );
  371. prevMaterial = elem.material;
  372. index0 = offset / 3;
  373. numGroupVerts = vertices.length;
  374. } else {
  375. numGroupVerts += vertices.length;
  376. }
  377. offset += 3 * vertices.length;
  378. }
  379. if ( numGroupVerts > 0 ) {
  380. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  381. }
  382. bufferGeometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  383. if ( normals !== null ) {
  384. bufferGeometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  385. }
  386. let object3d = null;
  387. if ( elementSize === 2 ) {
  388. object3d = new THREE.LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  389. } else if ( elementSize === 3 ) {
  390. object3d = new THREE.Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  391. }
  392. if ( isConditionalSegments ) {
  393. object3d.isConditionalLine = true;
  394. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  395. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  396. const directionArray = new Float32Array( elements.length * 3 * 2 );
  397. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  398. const os = elements[ i ];
  399. const vertices = os.vertices;
  400. const controlPoints = os.controlPoints;
  401. const c0 = controlPoints[ 0 ];
  402. const c1 = controlPoints[ 1 ];
  403. const v0 = vertices[ 0 ];
  404. const v1 = vertices[ 1 ];
  405. const index = i * 3 * 2;
  406. controlArray0[ index + 0 ] = c0.x;
  407. controlArray0[ index + 1 ] = c0.y;
  408. controlArray0[ index + 2 ] = c0.z;
  409. controlArray0[ index + 3 ] = c0.x;
  410. controlArray0[ index + 4 ] = c0.y;
  411. controlArray0[ index + 5 ] = c0.z;
  412. controlArray1[ index + 0 ] = c1.x;
  413. controlArray1[ index + 1 ] = c1.y;
  414. controlArray1[ index + 2 ] = c1.z;
  415. controlArray1[ index + 3 ] = c1.x;
  416. controlArray1[ index + 4 ] = c1.y;
  417. controlArray1[ index + 5 ] = c1.z;
  418. directionArray[ index + 0 ] = v1.x - v0.x;
  419. directionArray[ index + 1 ] = v1.y - v0.y;
  420. directionArray[ index + 2 ] = v1.z - v0.z;
  421. directionArray[ index + 3 ] = v1.x - v0.x;
  422. directionArray[ index + 4 ] = v1.y - v0.y;
  423. directionArray[ index + 5 ] = v1.z - v0.z;
  424. }
  425. bufferGeometry.setAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  426. bufferGeometry.setAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  427. bufferGeometry.setAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  428. }
  429. return object3d;
  430. } //
  431. class LDrawLoader extends THREE.Loader {
  432. constructor( manager ) {
  433. super( manager ); // This is a stack of 'parse scopes' with one level per subobject loaded file.
  434. // Each level contains a material lib and also other runtime variables passed between parent and child subobjects
  435. // When searching for a material code, the stack is read from top of the stack to bottom
  436. // Each material library is an object map keyed by colour codes.
  437. this.parseScopesStack = null; // Array of THREE.Material
  438. this.materials = []; // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  439. // This also allows to handle the embedded text files ("0 FILE" lines)
  440. this.subobjectCache = {}; // 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.
  441. this.fileMap = null; // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  442. 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.
  443. // If not (the default), only one object which contains all the merged primitives will be created.
  444. this.separateObjects = false; // If this flag is set to true the vertex normals will be smoothed.
  445. this.smoothNormals = true; // The path to load parts from the LDraw parts library from.
  446. this.partsLibraryPath = '';
  447. }
  448. setPartsLibraryPath( path ) {
  449. this.partsLibraryPath = path;
  450. return this;
  451. }
  452. async preloadMaterials( url ) {
  453. const fileLoader = new THREE.FileLoader( this.manager );
  454. fileLoader.setPath( this.path );
  455. fileLoader.setRequestHeader( this.requestHeader );
  456. fileLoader.setWithCredentials( this.withCredentials );
  457. const text = await fileLoader.loadAsync( url );
  458. const colorLineRegex = /^0 !COLOUR/;
  459. const lines = text.split( /[\n\r]/g );
  460. const materials = [];
  461. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  462. const line = lines[ i ];
  463. if ( colorLineRegex.test( line ) ) {
  464. const directive = line.replace( colorLineRegex, '' );
  465. const material = this.parseColourMetaDirective( new LineParser( directive ) );
  466. materials.push( material );
  467. }
  468. }
  469. this.setMaterials( materials );
  470. }
  471. load( url, onLoad, onProgress, onError ) {
  472. if ( ! this.fileMap ) {
  473. this.fileMap = {};
  474. }
  475. const scope = this;
  476. const fileLoader = new THREE.FileLoader( this.manager );
  477. fileLoader.setPath( this.path );
  478. fileLoader.setRequestHeader( this.requestHeader );
  479. fileLoader.setWithCredentials( this.withCredentials );
  480. fileLoader.load( url, function ( text ) {
  481. scope.processObject( text, onLoad, null, url );
  482. }, onProgress, onError );
  483. }
  484. parse( text, path, onLoad ) {
  485. // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
  486. this.processObject( text, onLoad, null, path );
  487. }
  488. setMaterials( materials ) {
  489. // Clears parse scopes stack, adds new scope with material library
  490. this.parseScopesStack = [];
  491. this.newParseScopeLevel( materials );
  492. this.getCurrentParseScope().isFromParse = false;
  493. this.materials = materials;
  494. return this;
  495. }
  496. setFileMap( fileMap ) {
  497. this.fileMap = fileMap;
  498. return this;
  499. }
  500. newParseScopeLevel( materials ) {
  501. // Adds a new scope level, assign materials to it and returns it
  502. const matLib = {};
  503. if ( materials ) {
  504. for ( let i = 0, n = materials.length; i < n; i ++ ) {
  505. const material = materials[ i ];
  506. matLib[ material.userData.code ] = material;
  507. }
  508. }
  509. const topParseScope = this.getCurrentParseScope();
  510. const newParseScope = {
  511. lib: matLib,
  512. url: null,
  513. // Subobjects
  514. subobjects: null,
  515. numSubobjects: 0,
  516. subobjectIndex: 0,
  517. inverted: false,
  518. category: null,
  519. keywords: null,
  520. // Current subobject
  521. currentFileName: null,
  522. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  523. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  524. currentMatrix: new THREE.Matrix4(),
  525. matrix: new THREE.Matrix4(),
  526. // If false, it is a root material scope previous to parse
  527. isFromParse: true,
  528. faces: null,
  529. lineSegments: null,
  530. conditionalSegments: null,
  531. totalFaces: 0,
  532. // If true, this object is the start of a construction step
  533. startingConstructionStep: false
  534. };
  535. this.parseScopesStack.push( newParseScope );
  536. return newParseScope;
  537. }
  538. removeScopeLevel() {
  539. this.parseScopesStack.pop();
  540. return this;
  541. }
  542. addMaterial( material ) {
  543. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  544. const matLib = this.getCurrentParseScope().lib;
  545. if ( ! matLib[ material.userData.code ] ) {
  546. this.materials.push( material );
  547. }
  548. matLib[ material.userData.code ] = material;
  549. return this;
  550. }
  551. getMaterial( colourCode ) {
  552. // Given a colour code search its material in the parse scopes stack
  553. if ( colourCode.startsWith( '0x2' ) ) {
  554. // Special 'direct' material value (RGB colour)
  555. const colour = colourCode.substring( 3 );
  556. return this.parseColourMetaDirective( new LineParser( 'Direct_Color_' + colour + ' CODE -1 VALUE #' + colour + ' EDGE #' + colour + '' ) );
  557. }
  558. for ( let i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  559. const material = this.parseScopesStack[ i ].lib[ colourCode ];
  560. if ( material ) {
  561. return material;
  562. }
  563. } // Material was not found
  564. return null;
  565. }
  566. getParentParseScope() {
  567. if ( this.parseScopesStack.length > 1 ) {
  568. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  569. }
  570. return null;
  571. }
  572. getCurrentParseScope() {
  573. if ( this.parseScopesStack.length > 0 ) {
  574. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  575. }
  576. return null;
  577. }
  578. parseColourMetaDirective( lineParser ) {
  579. // Parses a colour definition and returns a THREE.Material or null if error
  580. let code = null; // Triangle and line colours
  581. let colour = 0xFF00FF;
  582. let edgeColour = 0xFF00FF; // Transparency
  583. let alpha = 1;
  584. let isTransparent = false; // Self-illumination:
  585. let luminance = 0;
  586. let finishType = FINISH_TYPE_DEFAULT;
  587. let edgeMaterial = null;
  588. const name = lineParser.getToken();
  589. if ( ! name ) {
  590. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.';
  591. } // Parse tag tokens and their parameters
  592. let token = null;
  593. while ( true ) {
  594. token = lineParser.getToken();
  595. if ( ! token ) {
  596. break;
  597. }
  598. switch ( token.toUpperCase() ) {
  599. case 'CODE':
  600. code = lineParser.getToken();
  601. break;
  602. case 'VALUE':
  603. colour = lineParser.getToken();
  604. if ( colour.startsWith( '0x' ) ) {
  605. colour = '#' + colour.substring( 2 );
  606. } else if ( ! colour.startsWith( '#' ) ) {
  607. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + '.';
  608. }
  609. break;
  610. case 'EDGE':
  611. edgeColour = lineParser.getToken();
  612. if ( edgeColour.startsWith( '0x' ) ) {
  613. edgeColour = '#' + edgeColour.substring( 2 );
  614. } else if ( ! edgeColour.startsWith( '#' ) ) {
  615. // Try to see if edge colour is a colour code
  616. edgeMaterial = this.getMaterial( edgeColour );
  617. if ( ! edgeMaterial ) {
  618. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + '.';
  619. } // Get the edge material for this triangle material
  620. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  621. }
  622. break;
  623. case 'ALPHA':
  624. alpha = parseInt( lineParser.getToken() );
  625. if ( isNaN( alpha ) ) {
  626. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.';
  627. }
  628. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  629. if ( alpha < 1 ) {
  630. isTransparent = true;
  631. }
  632. break;
  633. case 'LUMINANCE':
  634. luminance = parseInt( lineParser.getToken() );
  635. if ( isNaN( luminance ) ) {
  636. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.';
  637. }
  638. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  639. break;
  640. case 'CHROME':
  641. finishType = FINISH_TYPE_CHROME;
  642. break;
  643. case 'PEARLESCENT':
  644. finishType = FINISH_TYPE_PEARLESCENT;
  645. break;
  646. case 'RUBBER':
  647. finishType = FINISH_TYPE_RUBBER;
  648. break;
  649. case 'MATTE_METALLIC':
  650. finishType = FINISH_TYPE_MATTE_METALLIC;
  651. break;
  652. case 'METAL':
  653. finishType = FINISH_TYPE_METAL;
  654. break;
  655. case 'MATERIAL':
  656. // Not implemented
  657. lineParser.setToEnd();
  658. break;
  659. default:
  660. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.';
  661. break;
  662. }
  663. }
  664. let material = null;
  665. switch ( finishType ) {
  666. case FINISH_TYPE_DEFAULT:
  667. material = new THREE.MeshStandardMaterial( {
  668. color: colour,
  669. roughness: 0.3,
  670. metalness: 0
  671. } );
  672. break;
  673. case FINISH_TYPE_PEARLESCENT:
  674. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  675. const specular = new THREE.Color( colour );
  676. const hsl = specular.getHSL( {
  677. h: 0,
  678. s: 0,
  679. l: 0
  680. } );
  681. hsl.h = ( hsl.h + 0.5 ) % 1;
  682. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  683. specular.setHSL( hsl.h, hsl.s, hsl.l );
  684. material = new THREE.MeshPhongMaterial( {
  685. color: colour,
  686. specular: specular,
  687. shininess: 10,
  688. reflectivity: 0.3
  689. } );
  690. break;
  691. case FINISH_TYPE_CHROME:
  692. // Mirror finish surface
  693. material = new THREE.MeshStandardMaterial( {
  694. color: colour,
  695. roughness: 0,
  696. metalness: 1
  697. } );
  698. break;
  699. case FINISH_TYPE_RUBBER:
  700. // Rubber finish
  701. material = new THREE.MeshStandardMaterial( {
  702. color: colour,
  703. roughness: 0.9,
  704. metalness: 0
  705. } );
  706. break;
  707. case FINISH_TYPE_MATTE_METALLIC:
  708. // Brushed metal finish
  709. material = new THREE.MeshStandardMaterial( {
  710. color: colour,
  711. roughness: 0.8,
  712. metalness: 0.4
  713. } );
  714. break;
  715. case FINISH_TYPE_METAL:
  716. // Average metal finish
  717. material = new THREE.MeshStandardMaterial( {
  718. color: colour,
  719. roughness: 0.2,
  720. metalness: 0.85
  721. } );
  722. break;
  723. default:
  724. // Should not happen
  725. break;
  726. }
  727. material.transparent = isTransparent;
  728. material.premultipliedAlpha = true;
  729. material.opacity = alpha;
  730. material.depthWrite = ! isTransparent;
  731. material.polygonOffset = true;
  732. material.polygonOffsetFactor = 1;
  733. if ( luminance !== 0 ) {
  734. material.emissive.set( material.color ).multiplyScalar( luminance );
  735. }
  736. if ( ! edgeMaterial ) {
  737. // This is the material used for edges
  738. edgeMaterial = new THREE.LineBasicMaterial( {
  739. color: edgeColour,
  740. transparent: isTransparent,
  741. opacity: alpha,
  742. depthWrite: ! isTransparent
  743. } );
  744. edgeMaterial.userData.code = code;
  745. edgeMaterial.name = name + ' - Edge'; // This is the material used for conditional edges
  746. edgeMaterial.userData.conditionalEdgeMaterial = new LDrawConditionalLineMaterial( {
  747. fog: true,
  748. transparent: isTransparent,
  749. depthWrite: ! isTransparent,
  750. color: edgeColour,
  751. opacity: alpha
  752. } );
  753. }
  754. material.userData.code = code;
  755. material.name = name;
  756. material.userData.edgeMaterial = edgeMaterial;
  757. return material;
  758. } //
  759. objectParse( text ) {
  760. // Retrieve data from the parent parse scope
  761. const parentParseScope = this.getParentParseScope(); // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  762. const mainColourCode = parentParseScope.mainColourCode;
  763. const mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  764. const currentParseScope = this.getCurrentParseScope(); // Parse result variables
  765. let faces;
  766. let lineSegments;
  767. let conditionalSegments;
  768. const subobjects = [];
  769. let category = null;
  770. let keywords = null;
  771. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  772. // This is faster than String.split with regex that splits on both
  773. text = text.replace( /\r\n/g, '\n' );
  774. }
  775. const lines = text.split( '\n' );
  776. const numLines = lines.length;
  777. let parsingEmbeddedFiles = false;
  778. let currentEmbeddedFileName = null;
  779. let currentEmbeddedText = null;
  780. let bfcCertified = false;
  781. let bfcCCW = true;
  782. let bfcInverted = false;
  783. let bfcCull = true;
  784. let type = '';
  785. let startingConstructionStep = false;
  786. const scope = this;
  787. function parseColourCode( lineParser, forEdge ) {
  788. // Parses next colour code and returns a THREE.Material
  789. let colourCode = lineParser.getToken();
  790. if ( ! forEdge && colourCode === '16' ) {
  791. colourCode = mainColourCode;
  792. }
  793. if ( forEdge && colourCode === '24' ) {
  794. colourCode = mainEdgeColourCode;
  795. }
  796. const material = scope.getMaterial( colourCode );
  797. if ( ! material ) {
  798. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  799. }
  800. return material;
  801. }
  802. function parseVector( lp ) {
  803. const v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  804. if ( ! scope.separateObjects ) {
  805. v.applyMatrix4( currentParseScope.currentMatrix );
  806. }
  807. return v;
  808. } // Parse all line commands
  809. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  810. const line = lines[ lineIndex ];
  811. if ( line.length === 0 ) continue;
  812. if ( parsingEmbeddedFiles ) {
  813. if ( line.startsWith( '0 FILE ' ) ) {
  814. // Save previous embedded file in the cache
  815. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText; // New embedded text file
  816. currentEmbeddedFileName = line.substring( 7 );
  817. currentEmbeddedText = '';
  818. } else {
  819. currentEmbeddedText += line + '\n';
  820. }
  821. continue;
  822. }
  823. const lp = new LineParser( line, lineIndex + 1 );
  824. lp.seekNonSpace();
  825. if ( lp.isAtTheEnd() ) {
  826. // Empty line
  827. continue;
  828. } // Parse the line type
  829. const lineType = lp.getToken();
  830. let material;
  831. let segment;
  832. let inverted;
  833. let ccw;
  834. let doubleSided;
  835. let v0, v1, v2, v3, c0, c1, faceNormal;
  836. switch ( lineType ) {
  837. // Line type 0: Comment or META
  838. case '0':
  839. // Parse meta directive
  840. const meta = lp.getToken();
  841. if ( meta ) {
  842. switch ( meta ) {
  843. case '!LDRAW_ORG':
  844. type = lp.getToken();
  845. currentParseScope.faces = [];
  846. currentParseScope.lineSegments = [];
  847. currentParseScope.conditionalSegments = [];
  848. currentParseScope.type = type;
  849. const isRoot = ! parentParseScope.isFromParse;
  850. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  851. currentParseScope.groupObject = new THREE.Group();
  852. currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
  853. } // If the scale of the object is negated then the triangle winding order
  854. // needs to be flipped.
  855. if ( currentParseScope.matrix.determinant() < 0 && ( scope.separateObjects && isPrimitiveType( type ) || ! scope.separateObjects ) ) {
  856. currentParseScope.inverted = ! currentParseScope.inverted;
  857. }
  858. faces = currentParseScope.faces;
  859. lineSegments = currentParseScope.lineSegments;
  860. conditionalSegments = currentParseScope.conditionalSegments;
  861. break;
  862. case '!COLOUR':
  863. material = this.parseColourMetaDirective( lp );
  864. if ( material ) {
  865. this.addMaterial( material );
  866. } else {
  867. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  868. }
  869. break;
  870. case '!CATEGORY':
  871. category = lp.getToken();
  872. break;
  873. case '!KEYWORDS':
  874. const newKeywords = lp.getRemainingString().split( ',' );
  875. if ( newKeywords.length > 0 ) {
  876. if ( ! keywords ) {
  877. keywords = [];
  878. }
  879. newKeywords.forEach( function ( keyword ) {
  880. keywords.push( keyword.trim() );
  881. } );
  882. }
  883. break;
  884. case 'FILE':
  885. if ( lineIndex > 0 ) {
  886. // Start embedded text files parsing
  887. parsingEmbeddedFiles = true;
  888. currentEmbeddedFileName = lp.getRemainingString();
  889. currentEmbeddedText = '';
  890. bfcCertified = false;
  891. bfcCCW = true;
  892. }
  893. break;
  894. case 'BFC':
  895. // Changes to the backface culling state
  896. while ( ! lp.isAtTheEnd() ) {
  897. const token = lp.getToken();
  898. switch ( token ) {
  899. case 'CERTIFY':
  900. case 'NOCERTIFY':
  901. bfcCertified = token === 'CERTIFY';
  902. bfcCCW = true;
  903. break;
  904. case 'CW':
  905. case 'CCW':
  906. bfcCCW = token === 'CCW';
  907. break;
  908. case 'INVERTNEXT':
  909. bfcInverted = true;
  910. break;
  911. case 'CLIP':
  912. case 'NOCLIP':
  913. bfcCull = token === 'CLIP';
  914. break;
  915. default:
  916. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  917. break;
  918. }
  919. }
  920. break;
  921. case 'STEP':
  922. startingConstructionStep = true;
  923. break;
  924. default:
  925. // Other meta directives are not implemented
  926. break;
  927. }
  928. }
  929. break;
  930. // Line type 1: Sub-object file
  931. case '1':
  932. material = parseColourCode( lp );
  933. const posX = parseFloat( lp.getToken() );
  934. const posY = parseFloat( lp.getToken() );
  935. const posZ = parseFloat( lp.getToken() );
  936. const m0 = parseFloat( lp.getToken() );
  937. const m1 = parseFloat( lp.getToken() );
  938. const m2 = parseFloat( lp.getToken() );
  939. const m3 = parseFloat( lp.getToken() );
  940. const m4 = parseFloat( lp.getToken() );
  941. const m5 = parseFloat( lp.getToken() );
  942. const m6 = parseFloat( lp.getToken() );
  943. const m7 = parseFloat( lp.getToken() );
  944. const m8 = parseFloat( lp.getToken() );
  945. const matrix = new THREE.Matrix4().set( m0, m1, m2, posX, m3, m4, m5, posY, m6, m7, m8, posZ, 0, 0, 0, 1 );
  946. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  947. if ( scope.fileMap[ fileName ] ) {
  948. // Found the subobject path in the preloaded file path map
  949. fileName = scope.fileMap[ fileName ];
  950. } else {
  951. // Standardized subfolders
  952. if ( fileName.startsWith( 's/' ) ) {
  953. fileName = 'parts/' + fileName;
  954. } else if ( fileName.startsWith( '48/' ) ) {
  955. fileName = 'p/' + fileName;
  956. }
  957. }
  958. subobjects.push( {
  959. material: material,
  960. matrix: matrix,
  961. fileName: fileName,
  962. originalFileName: fileName,
  963. locationState: FILE_LOCATION_AS_IS,
  964. url: null,
  965. triedLowerCase: false,
  966. inverted: bfcInverted !== currentParseScope.inverted,
  967. startingConstructionStep: startingConstructionStep
  968. } );
  969. bfcInverted = false;
  970. break;
  971. // Line type 2: Line segment
  972. case '2':
  973. material = parseColourCode( lp, true );
  974. v0 = parseVector( lp );
  975. v1 = parseVector( lp );
  976. segment = {
  977. material: material.userData.edgeMaterial,
  978. colourCode: material.userData.code,
  979. v0: v0,
  980. v1: v1,
  981. vertices: [ v0, v1 ]
  982. };
  983. lineSegments.push( segment );
  984. break;
  985. // Line type 5: Conditional Line segment
  986. case '5':
  987. material = parseColourCode( lp, true );
  988. v0 = parseVector( lp );
  989. v1 = parseVector( lp );
  990. c0 = parseVector( lp );
  991. c1 = parseVector( lp );
  992. segment = {
  993. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  994. colourCode: material.userData.code,
  995. vertices: [ v0, v1 ],
  996. controlPoints: [ c0, c1 ]
  997. };
  998. conditionalSegments.push( segment );
  999. break;
  1000. // Line type 3: Triangle
  1001. case '3':
  1002. material = parseColourCode( lp );
  1003. inverted = currentParseScope.inverted;
  1004. ccw = bfcCCW !== inverted;
  1005. doubleSided = ! bfcCertified || ! bfcCull;
  1006. if ( ccw === true ) {
  1007. v0 = parseVector( lp );
  1008. v1 = parseVector( lp );
  1009. v2 = parseVector( lp );
  1010. } else {
  1011. v2 = parseVector( lp );
  1012. v1 = parseVector( lp );
  1013. v0 = parseVector( lp );
  1014. }
  1015. _tempVec0.subVectors( v1, v0 );
  1016. _tempVec1.subVectors( v2, v1 );
  1017. faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize();
  1018. faces.push( {
  1019. material: material,
  1020. colourCode: material.userData.code,
  1021. faceNormal: faceNormal,
  1022. vertices: [ v0, v1, v2 ],
  1023. normals: [ null, null, null ]
  1024. } );
  1025. currentParseScope.totalFaces ++;
  1026. if ( doubleSided === true ) {
  1027. faces.push( {
  1028. material: material,
  1029. colourCode: material.userData.code,
  1030. faceNormal: faceNormal,
  1031. vertices: [ v2, v1, v0 ],
  1032. normals: [ null, null, null ]
  1033. } );
  1034. currentParseScope.totalFaces ++;
  1035. }
  1036. break;
  1037. // Line type 4: Quadrilateral
  1038. case '4':
  1039. material = parseColourCode( lp );
  1040. inverted = currentParseScope.inverted;
  1041. ccw = bfcCCW !== inverted;
  1042. doubleSided = ! bfcCertified || ! bfcCull;
  1043. if ( ccw === true ) {
  1044. v0 = parseVector( lp );
  1045. v1 = parseVector( lp );
  1046. v2 = parseVector( lp );
  1047. v3 = parseVector( lp );
  1048. } else {
  1049. v3 = parseVector( lp );
  1050. v2 = parseVector( lp );
  1051. v1 = parseVector( lp );
  1052. v0 = parseVector( lp );
  1053. }
  1054. _tempVec0.subVectors( v1, v0 );
  1055. _tempVec1.subVectors( v2, v1 );
  1056. faceNormal = new THREE.Vector3().crossVectors( _tempVec0, _tempVec1 ).normalize(); // specifically place the triangle diagonal in the v0 and v1 slots so we can
  1057. // account for the doubling of vertices later when smoothing normals.
  1058. faces.push( {
  1059. material: material,
  1060. colourCode: material.userData.code,
  1061. faceNormal: faceNormal,
  1062. vertices: [ v0, v1, v2, v3 ],
  1063. normals: [ null, null, null, null ]
  1064. } );
  1065. currentParseScope.totalFaces += 2;
  1066. if ( doubleSided === true ) {
  1067. faces.push( {
  1068. material: material,
  1069. colourCode: material.userData.code,
  1070. faceNormal: faceNormal,
  1071. vertices: [ v3, v2, v1, v0 ],
  1072. normals: [ null, null, null, null ]
  1073. } );
  1074. currentParseScope.totalFaces += 2;
  1075. }
  1076. break;
  1077. default:
  1078. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1079. break;
  1080. }
  1081. }
  1082. if ( parsingEmbeddedFiles ) {
  1083. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  1084. }
  1085. currentParseScope.category = category;
  1086. currentParseScope.keywords = keywords;
  1087. currentParseScope.subobjects = subobjects;
  1088. currentParseScope.numSubobjects = subobjects.length;
  1089. currentParseScope.subobjectIndex = 0;
  1090. }
  1091. computeConstructionSteps( model ) {
  1092. // Sets userdata.constructionStep number in THREE.Group objects and userData.numConstructionSteps number in the root THREE.Group object.
  1093. let stepNumber = 0;
  1094. model.traverse( c => {
  1095. if ( c.isGroup ) {
  1096. if ( c.userData.startingConstructionStep ) {
  1097. stepNumber ++;
  1098. }
  1099. c.userData.constructionStep = stepNumber;
  1100. }
  1101. } );
  1102. model.userData.numConstructionSteps = stepNumber + 1;
  1103. }
  1104. processObject( text, onProcessed, subobject, url ) {
  1105. const scope = this;
  1106. const parseScope = scope.newParseScopeLevel();
  1107. parseScope.url = url;
  1108. const parentParseScope = scope.getParentParseScope(); // Set current matrix
  1109. if ( subobject ) {
  1110. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  1111. parseScope.matrix.copy( subobject.matrix );
  1112. parseScope.inverted = subobject.inverted;
  1113. parseScope.startingConstructionStep = subobject.startingConstructionStep;
  1114. } // Add to cache
  1115. let currentFileName = parentParseScope.currentFileName;
  1116. if ( currentFileName !== null ) {
  1117. currentFileName = parentParseScope.currentFileName.toLowerCase();
  1118. }
  1119. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  1120. scope.subobjectCache[ currentFileName ] = text;
  1121. } // Parse the object (returns a THREE.Group)
  1122. scope.objectParse( text );
  1123. let finishedCount = 0;
  1124. onSubobjectFinish();
  1125. function onSubobjectFinish() {
  1126. finishedCount ++;
  1127. if ( finishedCount === parseScope.subobjects.length + 1 ) {
  1128. finalizeObject();
  1129. } else {
  1130. // Once the previous subobject has finished we can start processing the next one in the list.
  1131. // The subobject processing shares scope in processing so it's important that they be loaded serially
  1132. // to avoid race conditions.
  1133. // Promise.resolve is used as an approach to asynchronously schedule a task _before_ this frame ends to
  1134. // avoid stack overflow exceptions when loading many subobjects from the cache. RequestAnimationFrame
  1135. // will work but causes the load to happen after the next frame which causes the load to take significantly longer.
  1136. const subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  1137. Promise.resolve().then( function () {
  1138. loadSubobject( subobject );
  1139. } );
  1140. parseScope.subobjectIndex ++;
  1141. }
  1142. }
  1143. function finalizeObject() {
  1144. if ( scope.smoothNormals && parseScope.type === 'Part' ) {
  1145. smoothNormals( parseScope.faces, parseScope.lineSegments );
  1146. }
  1147. const isRoot = ! parentParseScope.isFromParse;
  1148. if ( scope.separateObjects && ! isPrimitiveType( parseScope.type ) || isRoot ) {
  1149. const objGroup = parseScope.groupObject;
  1150. if ( parseScope.faces.length > 0 ) {
  1151. objGroup.add( createObject( parseScope.faces, 3, false, parseScope.totalFaces ) );
  1152. }
  1153. if ( parseScope.lineSegments.length > 0 ) {
  1154. objGroup.add( createObject( parseScope.lineSegments, 2 ) );
  1155. }
  1156. if ( parseScope.conditionalSegments.length > 0 ) {
  1157. objGroup.add( createObject( parseScope.conditionalSegments, 2, true ) );
  1158. }
  1159. if ( parentParseScope.groupObject ) {
  1160. objGroup.name = parseScope.fileName;
  1161. objGroup.userData.category = parseScope.category;
  1162. objGroup.userData.keywords = parseScope.keywords;
  1163. parseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  1164. parentParseScope.groupObject.add( objGroup );
  1165. }
  1166. } else {
  1167. const separateObjects = scope.separateObjects;
  1168. const parentLineSegments = parentParseScope.lineSegments;
  1169. const parentConditionalSegments = parentParseScope.conditionalSegments;
  1170. const parentFaces = parentParseScope.faces;
  1171. const lineSegments = parseScope.lineSegments;
  1172. const conditionalSegments = parseScope.conditionalSegments;
  1173. const faces = parseScope.faces;
  1174. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  1175. const ls = lineSegments[ i ];
  1176. if ( separateObjects ) {
  1177. const vertices = ls.vertices;
  1178. vertices[ 0 ].applyMatrix4( parseScope.matrix );
  1179. vertices[ 1 ].applyMatrix4( parseScope.matrix );
  1180. }
  1181. parentLineSegments.push( ls );
  1182. }
  1183. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  1184. const os = conditionalSegments[ i ];
  1185. if ( separateObjects ) {
  1186. const vertices = os.vertices;
  1187. const controlPoints = os.controlPoints;
  1188. vertices[ 0 ].applyMatrix4( parseScope.matrix );
  1189. vertices[ 1 ].applyMatrix4( parseScope.matrix );
  1190. controlPoints[ 0 ].applyMatrix4( parseScope.matrix );
  1191. controlPoints[ 1 ].applyMatrix4( parseScope.matrix );
  1192. }
  1193. parentConditionalSegments.push( os );
  1194. }
  1195. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  1196. const tri = faces[ i ];
  1197. if ( separateObjects ) {
  1198. const vertices = tri.vertices;
  1199. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  1200. vertices[ i ] = vertices[ i ].clone().applyMatrix4( parseScope.matrix );
  1201. }
  1202. _tempVec0.subVectors( vertices[ 1 ], vertices[ 0 ] );
  1203. _tempVec1.subVectors( vertices[ 2 ], vertices[ 1 ] );
  1204. tri.faceNormal.crossVectors( _tempVec0, _tempVec1 ).normalize();
  1205. }
  1206. parentFaces.push( tri );
  1207. }
  1208. parentParseScope.totalFaces += parseScope.totalFaces;
  1209. }
  1210. scope.removeScopeLevel(); // If it is root object, compute construction steps
  1211. if ( ! parentParseScope.isFromParse ) {
  1212. scope.computeConstructionSteps( parseScope.groupObject );
  1213. }
  1214. if ( onProcessed ) {
  1215. onProcessed( parseScope.groupObject );
  1216. }
  1217. }
  1218. function loadSubobject( subobject ) {
  1219. parseScope.mainColourCode = subobject.material.userData.code;
  1220. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  1221. parseScope.currentFileName = subobject.originalFileName; // If subobject was cached previously, use the cached one
  1222. const cached = scope.subobjectCache[ subobject.originalFileName.toLowerCase() ];
  1223. if ( cached ) {
  1224. scope.processObject( cached, function ( subobjectGroup ) {
  1225. onSubobjectLoaded( subobjectGroup, subobject );
  1226. onSubobjectFinish();
  1227. }, subobject, url );
  1228. return;
  1229. } // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  1230. // Update also subobject.locationState for the next try if this load fails.
  1231. let subobjectURL = subobject.fileName;
  1232. let newLocationState = FILE_LOCATION_NOT_FOUND;
  1233. switch ( subobject.locationState ) {
  1234. case FILE_LOCATION_AS_IS:
  1235. newLocationState = subobject.locationState + 1;
  1236. break;
  1237. case FILE_LOCATION_TRY_PARTS:
  1238. subobjectURL = 'parts/' + subobjectURL;
  1239. newLocationState = subobject.locationState + 1;
  1240. break;
  1241. case FILE_LOCATION_TRY_P:
  1242. subobjectURL = 'p/' + subobjectURL;
  1243. newLocationState = subobject.locationState + 1;
  1244. break;
  1245. case FILE_LOCATION_TRY_MODELS:
  1246. subobjectURL = 'models/' + subobjectURL;
  1247. newLocationState = subobject.locationState + 1;
  1248. break;
  1249. case FILE_LOCATION_TRY_RELATIVE:
  1250. subobjectURL = url.substring( 0, url.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  1251. newLocationState = subobject.locationState + 1;
  1252. break;
  1253. case FILE_LOCATION_TRY_ABSOLUTE:
  1254. if ( subobject.triedLowerCase ) {
  1255. // Try absolute path
  1256. newLocationState = FILE_LOCATION_NOT_FOUND;
  1257. } else {
  1258. // Next attempt is lower case
  1259. subobject.fileName = subobject.fileName.toLowerCase();
  1260. subobjectURL = subobject.fileName;
  1261. subobject.triedLowerCase = true;
  1262. newLocationState = FILE_LOCATION_AS_IS;
  1263. }
  1264. break;
  1265. case FILE_LOCATION_NOT_FOUND:
  1266. // All location possibilities have been tried, give up loading this object
  1267. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  1268. return;
  1269. }
  1270. subobject.locationState = newLocationState;
  1271. subobject.url = subobjectURL; // Load the subobject
  1272. // Use another file loader here so we can keep track of the subobject information
  1273. // and use it when processing the next model.
  1274. const fileLoader = new THREE.FileLoader( scope.manager );
  1275. fileLoader.setPath( scope.partsLibraryPath );
  1276. fileLoader.setRequestHeader( scope.requestHeader );
  1277. fileLoader.setWithCredentials( scope.withCredentials );
  1278. fileLoader.load( subobjectURL, function ( text ) {
  1279. scope.processObject( text, function ( subobjectGroup ) {
  1280. onSubobjectLoaded( subobjectGroup, subobject );
  1281. onSubobjectFinish();
  1282. }, subobject, url );
  1283. }, undefined, function ( err ) {
  1284. onSubobjectError( err, subobject );
  1285. }, subobject );
  1286. }
  1287. function onSubobjectLoaded( subobjectGroup, subobject ) {
  1288. if ( subobjectGroup === null ) {
  1289. // Try to reload
  1290. loadSubobject( subobject );
  1291. return;
  1292. }
  1293. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  1294. }
  1295. function onSubobjectError( err, subobject ) {
  1296. // Retry download from a different default possible location
  1297. loadSubobject( subobject );
  1298. }
  1299. }
  1300. }
  1301. THREE.LDrawLoader = LDrawLoader;
  1302. } )();