2
0

LDrawLoader.js 45 KB

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