LDrawLoader.js 45 KB

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