LDrawLoader.js 45 KB

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