LDrawLoader.js 45 KB

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