LDrawLoader.js 45 KB

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