LDrawLoader.js 46 KB

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