LDrawLoader.js 46 KB

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