LDrawLoader.js 46 KB

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