LDrawLoader.js 46 KB

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