LDrawLoader.js 46 KB

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