2
0

LDrawLoader.js 45 KB

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