LDrawLoader.js 44 KB

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