LDrawLoader.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954
  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 <premultiplied_alpha_fragment>
  67. #include <tonemapping_fragment>
  68. #include <encodings_fragment>
  69. #include <fog_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.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
  300. if ( elementSize === 3 ) {
  301. bufferGeometry.addAttribute( '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.addAttribute( 'control0', new THREE.BufferAttribute( controlArray0, 3, false ) );
  341. bufferGeometry.addAttribute( 'control1', new THREE.BufferAttribute( controlArray1, 3, false ) );
  342. bufferGeometry.addAttribute( 'direction', new THREE.BufferAttribute( directionArray, 3, false ) );
  343. }
  344. return object3d;
  345. }
  346. //
  347. function LDrawLoader( manager ) {
  348. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  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. this.path = '';
  355. // Array of THREE.Material
  356. this.materials = [];
  357. // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  358. // This also allows to handle the embedded text files ("0 FILE" lines)
  359. this.subobjectCache = {};
  360. // 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.
  361. this.fileMap = null;
  362. // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  363. this.setMaterials( [
  364. this.parseColourMetaDirective( new LineParser( "Main_Colour CODE 16 VALUE #FF8080 EDGE #333333" ) ),
  365. this.parseColourMetaDirective( new LineParser( "Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333" ) )
  366. ] );
  367. // If this flag is set to true, each subobject will be a THREE.Object.
  368. // If not (the default), only one object which contains all the merged primitives will be created.
  369. this.separateObjects = false;
  370. // If this flag is set to true the vertex normals will be smoothed.
  371. this.smoothNormals = true;
  372. }
  373. // Special surface finish tag types.
  374. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  375. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  376. LDrawLoader.FINISH_TYPE_CHROME = 1;
  377. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  378. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  379. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  380. LDrawLoader.FINISH_TYPE_METAL = 5;
  381. // State machine to search a subobject path.
  382. // The LDraw standard establishes these various possible subfolders.
  383. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  384. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  385. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  386. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  387. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  388. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  389. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  390. LDrawLoader.prototype = {
  391. constructor: LDrawLoader,
  392. load: function ( url, onLoad, onProgress, onError ) {
  393. if ( ! this.fileMap ) {
  394. this.fileMap = {};
  395. }
  396. var scope = this;
  397. var fileLoader = new THREE.FileLoader( this.manager );
  398. fileLoader.setPath( this.path );
  399. fileLoader.load( url, function ( text ) {
  400. scope.processObject( text, onLoad, null, url );
  401. }, onProgress, onError );
  402. },
  403. parse: function ( text, path, onLoad ) {
  404. // Async parse. This function calls onParse with the parsed THREE.Object3D as parameter
  405. this.processObject( text, onLoad, null, path );
  406. },
  407. setPath: function ( value ) {
  408. this.path = value;
  409. return this;
  410. },
  411. setMaterials: function ( materials ) {
  412. // Clears parse scopes stack, adds new scope with material library
  413. this.parseScopesStack = [];
  414. this.newParseScopeLevel( materials );
  415. this.getCurrentParseScope().isFromParse = false;
  416. this.materials = materials;
  417. return this;
  418. },
  419. setFileMap: function ( fileMap ) {
  420. this.fileMap = fileMap;
  421. return this;
  422. },
  423. newParseScopeLevel: function ( materials ) {
  424. // Adds a new scope level, assign materials to it and returns it
  425. var matLib = {};
  426. if ( materials ) {
  427. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  428. var material = materials[ i ];
  429. matLib[ material.userData.code ] = material;
  430. }
  431. }
  432. var topParseScope = this.getCurrentParseScope();
  433. var newParseScope = {
  434. lib: matLib,
  435. url: null,
  436. // Subobjects
  437. subobjects: null,
  438. numSubobjects: 0,
  439. subobjectIndex: 0,
  440. inverted: false,
  441. category: null,
  442. keywords: null,
  443. // Current subobject
  444. currentFileName: null,
  445. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  446. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  447. currentMatrix: new THREE.Matrix4(),
  448. matrix: new THREE.Matrix4(),
  449. // If false, it is a root material scope previous to parse
  450. isFromParse: true,
  451. triangles: null,
  452. lineSegments: null,
  453. conditionalSegments: null,
  454. // If true, this object is the start of a construction step
  455. startingConstructionStep: false
  456. };
  457. this.parseScopesStack.push( newParseScope );
  458. return newParseScope;
  459. },
  460. removeScopeLevel: function () {
  461. this.parseScopesStack.pop();
  462. return this;
  463. },
  464. addMaterial: function ( material ) {
  465. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  466. var matLib = this.getCurrentParseScope().lib;
  467. if ( ! matLib[ material.userData.code ] ) {
  468. this.materials.push( material );
  469. }
  470. matLib[ material.userData.code ] = material;
  471. return this;
  472. },
  473. getMaterial: function ( colourCode ) {
  474. // Given a colour code search its material in the parse scopes stack
  475. if ( colourCode.startsWith( "0x2" ) ) {
  476. // Special 'direct' material value (RGB colour)
  477. var colour = colourCode.substring( 3 );
  478. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  479. }
  480. for ( var i = this.parseScopesStack.length - 1; i >= 0; i -- ) {
  481. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  482. if ( material ) {
  483. return material;
  484. }
  485. }
  486. // Material was not found
  487. return null;
  488. },
  489. getParentParseScope: function () {
  490. if ( this.parseScopesStack.length > 1 ) {
  491. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  492. }
  493. return null;
  494. },
  495. getCurrentParseScope: function () {
  496. if ( this.parseScopesStack.length > 0 ) {
  497. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  498. }
  499. return null;
  500. },
  501. parseColourMetaDirective: function ( lineParser ) {
  502. // Parses a colour definition and returns a THREE.Material or null if error
  503. var code = null;
  504. // Triangle and line colours
  505. var colour = 0xFF00FF;
  506. var edgeColour = 0xFF00FF;
  507. // Transparency
  508. var alpha = 1;
  509. var isTransparent = false;
  510. // Self-illumination:
  511. var luminance = 0;
  512. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  513. var canHaveEnvMap = true;
  514. var edgeMaterial = null;
  515. var name = lineParser.getToken();
  516. if ( ! name ) {
  517. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  518. }
  519. // Parse tag tokens and their parameters
  520. var token = null;
  521. while ( true ) {
  522. token = lineParser.getToken();
  523. if ( ! token ) {
  524. break;
  525. }
  526. switch ( token.toUpperCase() ) {
  527. case "CODE":
  528. code = lineParser.getToken();
  529. break;
  530. case "VALUE":
  531. colour = lineParser.getToken();
  532. if ( colour.startsWith( '0x' ) ) {
  533. colour = '#' + colour.substring( 2 );
  534. } else if ( ! colour.startsWith( '#' ) ) {
  535. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  536. }
  537. break;
  538. case "EDGE":
  539. edgeColour = lineParser.getToken();
  540. if ( edgeColour.startsWith( '0x' ) ) {
  541. edgeColour = '#' + edgeColour.substring( 2 );
  542. } else if ( ! edgeColour.startsWith( '#' ) ) {
  543. // Try to see if edge colour is a colour code
  544. edgeMaterial = this.getMaterial( edgeColour );
  545. if ( ! edgeMaterial ) {
  546. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  547. }
  548. // Get the edge material for this triangle material
  549. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  550. }
  551. break;
  552. case 'ALPHA':
  553. alpha = parseInt( lineParser.getToken() );
  554. if ( isNaN( alpha ) ) {
  555. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  556. }
  557. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  558. if ( alpha < 1 ) {
  559. isTransparent = true;
  560. }
  561. break;
  562. case 'LUMINANCE':
  563. luminance = parseInt( lineParser.getToken() );
  564. if ( isNaN( luminance ) ) {
  565. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  566. }
  567. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  568. break;
  569. case 'CHROME':
  570. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  571. break;
  572. case 'PEARLESCENT':
  573. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  574. break;
  575. case 'RUBBER':
  576. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  577. break;
  578. case 'MATTE_METALLIC':
  579. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  580. break;
  581. case 'METAL':
  582. finishType = LDrawLoader.FINISH_TYPE_METAL;
  583. break;
  584. case 'MATERIAL':
  585. // Not implemented
  586. lineParser.setToEnd();
  587. break;
  588. default:
  589. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  590. break;
  591. }
  592. }
  593. var material = null;
  594. switch ( finishType ) {
  595. case LDrawLoader.FINISH_TYPE_DEFAULT:
  596. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.3, envMapIntensity: 0.3, metalness: 0 } );
  597. break;
  598. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  599. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  600. var specular = new THREE.Color( colour );
  601. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  602. hsl.h = ( hsl.h + 0.5 ) % 1;
  603. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  604. specular.setHSL( hsl.h, hsl.s, hsl.l );
  605. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: 10, reflectivity: 0.3 } );
  606. break;
  607. case LDrawLoader.FINISH_TYPE_CHROME:
  608. // Mirror finish surface
  609. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  610. break;
  611. case LDrawLoader.FINISH_TYPE_RUBBER:
  612. // Rubber finish
  613. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.9, metalness: 0 } );
  614. canHaveEnvMap = false;
  615. break;
  616. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  617. // Brushed metal finish
  618. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  619. break;
  620. case LDrawLoader.FINISH_TYPE_METAL:
  621. // Average metal finish
  622. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  623. break;
  624. default:
  625. // Should not happen
  626. break;
  627. }
  628. material.transparent = isTransparent;
  629. material.premultipliedAlpha = true;
  630. material.opacity = alpha;
  631. material.depthWrite = ! isTransparent;
  632. material.polygonOffset = true;
  633. material.polygonOffsetFactor = 1;
  634. material.userData.canHaveEnvMap = canHaveEnvMap;
  635. if ( luminance !== 0 ) {
  636. material.emissive.set( material.color ).multiplyScalar( luminance );
  637. }
  638. if ( ! edgeMaterial ) {
  639. // This is the material used for edges
  640. edgeMaterial = new THREE.LineBasicMaterial( {
  641. color: edgeColour,
  642. transparent: isTransparent,
  643. opacity: alpha,
  644. depthWrite: ! isTransparent
  645. } );
  646. edgeMaterial.userData.code = code;
  647. edgeMaterial.name = name + " - Edge";
  648. edgeMaterial.userData.canHaveEnvMap = false;
  649. // This is the material used for conditional edges
  650. edgeMaterial.userData.conditionalEdgeMaterial = new THREE.ShaderMaterial( {
  651. vertexShader: conditionalLineVertShader,
  652. fragmentShader: conditionalLineFragShader,
  653. uniforms: {
  654. diffuse: {
  655. value: new THREE.Color( edgeColour )
  656. },
  657. opacity: {
  658. value: alpha
  659. }
  660. },
  661. transparent: isTransparent,
  662. depthWrite: ! isTransparent
  663. } );
  664. edgeMaterial.userData.conditionalEdgeMaterial.userData.canHaveEnvMap = false;
  665. }
  666. material.userData.code = code;
  667. material.name = name;
  668. material.userData.edgeMaterial = edgeMaterial;
  669. return material;
  670. },
  671. //
  672. objectParse: function ( text ) {
  673. //console.time( 'LDrawLoader' );
  674. // Retrieve data from the parent parse scope
  675. var parentParseScope = this.getParentParseScope();
  676. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  677. var mainColourCode = parentParseScope.mainColourCode;
  678. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  679. var currentParseScope = this.getCurrentParseScope();
  680. // Parse result variables
  681. var triangles;
  682. var lineSegments;
  683. var conditionalSegments;
  684. var subobjects = [];
  685. var category = null;
  686. var keywords = null;
  687. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  688. // This is faster than String.split with regex that splits on both
  689. text = text.replace( /\r\n/g, '\n' );
  690. }
  691. var lines = text.split( '\n' );
  692. var numLines = lines.length;
  693. var lineIndex = 0;
  694. var parsingEmbeddedFiles = false;
  695. var currentEmbeddedFileName = null;
  696. var currentEmbeddedText = null;
  697. var bfcCertified = false;
  698. var bfcCCW = true;
  699. var bfcInverted = false;
  700. var bfcCull = true;
  701. var type = '';
  702. var startingConstructionStep = false;
  703. var scope = this;
  704. function parseColourCode( lineParser, forEdge ) {
  705. // Parses next colour code and returns a THREE.Material
  706. var colourCode = lineParser.getToken();
  707. if ( ! forEdge && colourCode === '16' ) {
  708. colourCode = mainColourCode;
  709. }
  710. if ( forEdge && colourCode === '24' ) {
  711. colourCode = mainEdgeColourCode;
  712. }
  713. var material = scope.getMaterial( colourCode );
  714. if ( ! material ) {
  715. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  716. }
  717. return material;
  718. }
  719. function parseVector( lp ) {
  720. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  721. if ( ! scope.separateObjects ) {
  722. v.applyMatrix4( currentParseScope.currentMatrix );
  723. }
  724. return v;
  725. }
  726. // Parse all line commands
  727. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  728. var line = lines[ lineIndex ];
  729. if ( line.length === 0 ) continue;
  730. if ( parsingEmbeddedFiles ) {
  731. if ( line.startsWith( '0 FILE ' ) ) {
  732. // Save previous embedded file in the cache
  733. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  734. // New embedded text file
  735. currentEmbeddedFileName = line.substring( 7 );
  736. currentEmbeddedText = '';
  737. } else {
  738. currentEmbeddedText += line + '\n';
  739. }
  740. continue;
  741. }
  742. var lp = new LineParser( line, lineIndex + 1 );
  743. lp.seekNonSpace();
  744. if ( lp.isAtTheEnd() ) {
  745. // Empty line
  746. continue;
  747. }
  748. // Parse the line type
  749. var lineType = lp.getToken();
  750. switch ( lineType ) {
  751. // Line type 0: Comment or META
  752. case '0':
  753. // Parse meta directive
  754. var meta = lp.getToken();
  755. if ( meta ) {
  756. switch ( meta ) {
  757. case '!LDRAW_ORG':
  758. type = lp.getToken();
  759. if ( ! parsingEmbeddedFiles ) {
  760. currentParseScope.triangles = [];
  761. currentParseScope.lineSegments = [];
  762. currentParseScope.conditionalSegments = [];
  763. currentParseScope.type = type;
  764. var isRoot = ! parentParseScope.isFromParse;
  765. if ( isRoot || scope.separateObjects && ! isPrimitiveType( type ) ) {
  766. currentParseScope.groupObject = new THREE.Group();
  767. currentParseScope.groupObject.userData.startingConstructionStep = currentParseScope.startingConstructionStep;
  768. }
  769. // If the scale of the object is negated then the triangle winding order
  770. // needs to be flipped.
  771. var matrix = currentParseScope.matrix;
  772. if (
  773. matrix.determinant() < 0 && (
  774. scope.separateObjects && isPrimitiveType( type ) ||
  775. ! scope.separateObjects
  776. ) ) {
  777. currentParseScope.inverted = ! currentParseScope.inverted;
  778. }
  779. triangles = currentParseScope.triangles;
  780. lineSegments = currentParseScope.lineSegments;
  781. conditionalSegments = currentParseScope.conditionalSegments;
  782. }
  783. break;
  784. case '!COLOUR':
  785. var material = this.parseColourMetaDirective( lp );
  786. if ( material ) {
  787. this.addMaterial( material );
  788. } else {
  789. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  790. }
  791. break;
  792. case '!CATEGORY':
  793. category = lp.getToken();
  794. break;
  795. case '!KEYWORDS':
  796. var newKeywords = lp.getRemainingString().split( ',' );
  797. if ( newKeywords.length > 0 ) {
  798. if ( ! keywords ) {
  799. keywords = [];
  800. }
  801. newKeywords.forEach( function ( keyword ) {
  802. keywords.push( keyword.trim() );
  803. } );
  804. }
  805. break;
  806. case 'FILE':
  807. if ( lineIndex > 0 ) {
  808. // Start embedded text files parsing
  809. parsingEmbeddedFiles = true;
  810. currentEmbeddedFileName = lp.getRemainingString();
  811. currentEmbeddedText = '';
  812. bfcCertified = false;
  813. bfcCCW = true;
  814. }
  815. break;
  816. case 'BFC':
  817. // Changes to the backface culling state
  818. while ( ! lp.isAtTheEnd() ) {
  819. var token = lp.getToken();
  820. switch ( token ) {
  821. case 'CERTIFY':
  822. case 'NOCERTIFY':
  823. bfcCertified = token === 'CERTIFY';
  824. bfcCCW = true;
  825. break;
  826. case 'CW':
  827. case 'CCW':
  828. bfcCCW = token === 'CCW';
  829. break;
  830. case 'INVERTNEXT':
  831. bfcInverted = true;
  832. break;
  833. case 'CLIP':
  834. case 'NOCLIP':
  835. bfcCull = token === 'CLIP';
  836. break;
  837. default:
  838. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  839. break;
  840. }
  841. }
  842. break;
  843. case 'STEP':
  844. startingConstructionStep = true;
  845. break;
  846. default:
  847. // Other meta directives are not implemented
  848. break;
  849. }
  850. }
  851. break;
  852. // Line type 1: Sub-object file
  853. case '1':
  854. var material = parseColourCode( lp );
  855. var posX = parseFloat( lp.getToken() );
  856. var posY = parseFloat( lp.getToken() );
  857. var posZ = parseFloat( lp.getToken() );
  858. var m0 = parseFloat( lp.getToken() );
  859. var m1 = parseFloat( lp.getToken() );
  860. var m2 = parseFloat( lp.getToken() );
  861. var m3 = parseFloat( lp.getToken() );
  862. var m4 = parseFloat( lp.getToken() );
  863. var m5 = parseFloat( lp.getToken() );
  864. var m6 = parseFloat( lp.getToken() );
  865. var m7 = parseFloat( lp.getToken() );
  866. var m8 = parseFloat( lp.getToken() );
  867. var matrix = new THREE.Matrix4().set(
  868. m0, m1, m2, posX,
  869. m3, m4, m5, posY,
  870. m6, m7, m8, posZ,
  871. 0, 0, 0, 1
  872. );
  873. var fileName = lp.getRemainingString().trim().replace( /\\/g, "/" );
  874. if ( scope.fileMap[ fileName ] ) {
  875. // Found the subobject path in the preloaded file path map
  876. fileName = scope.fileMap[ fileName ];
  877. } else {
  878. // Standardized subfolders
  879. if ( fileName.startsWith( 's/' ) ) {
  880. fileName = 'parts/' + fileName;
  881. } else if ( fileName.startsWith( '48/' ) ) {
  882. fileName = 'p/' + fileName;
  883. }
  884. }
  885. subobjects.push( {
  886. material: material,
  887. matrix: matrix,
  888. fileName: fileName,
  889. originalFileName: fileName,
  890. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  891. url: null,
  892. triedLowerCase: false,
  893. inverted: bfcInverted !== currentParseScope.inverted,
  894. startingConstructionStep: startingConstructionStep
  895. } );
  896. bfcInverted = false;
  897. break;
  898. // Line type 2: Line segment
  899. case '2':
  900. var material = parseColourCode( lp, true );
  901. var segment = {
  902. material: material.userData.edgeMaterial,
  903. colourCode: material.userData.code,
  904. v0: parseVector( lp ),
  905. v1: parseVector( lp )
  906. };
  907. lineSegments.push( segment );
  908. break;
  909. // Line type 5: Conditional Line segment
  910. case '5':
  911. var material = parseColourCode( lp, true );
  912. var segment = {
  913. material: material.userData.edgeMaterial.userData.conditionalEdgeMaterial,
  914. colourCode: material.userData.code,
  915. v0: parseVector( lp ),
  916. v1: parseVector( lp ),
  917. c0: parseVector( lp ),
  918. c1: parseVector( lp )
  919. };
  920. conditionalSegments.push( segment );
  921. break;
  922. // Line type 3: Triangle
  923. case '3':
  924. var material = parseColourCode( lp );
  925. var inverted = currentParseScope.inverted;
  926. var ccw = bfcCCW !== inverted;
  927. var doubleSided = ! bfcCertified || ! bfcCull;
  928. var v0, v1, v2, faceNormal;
  929. if ( ccw === true ) {
  930. v0 = parseVector( lp );
  931. v1 = parseVector( lp );
  932. v2 = parseVector( lp );
  933. } else {
  934. v2 = parseVector( lp );
  935. v1 = parseVector( lp );
  936. v0 = parseVector( lp );
  937. }
  938. tempVec0.subVectors( v1, v0 );
  939. tempVec1.subVectors( v2, v1 );
  940. faceNormal = new THREE.Vector3()
  941. .crossVectors( tempVec0, tempVec1 )
  942. .normalize();
  943. triangles.push( {
  944. material: material,
  945. colourCode: material.userData.code,
  946. v0: v0,
  947. v1: v1,
  948. v2: v2,
  949. faceNormal: faceNormal,
  950. n0: null,
  951. n1: null,
  952. n2: null
  953. } );
  954. if ( doubleSided === true ) {
  955. triangles.push( {
  956. material: material,
  957. colourCode: material.userData.code,
  958. v0: v0,
  959. v1: v2,
  960. v2: v1,
  961. faceNormal: faceNormal,
  962. n0: null,
  963. n1: null,
  964. n2: null
  965. } );
  966. }
  967. break;
  968. // Line type 4: Quadrilateral
  969. case '4':
  970. var material = parseColourCode( lp );
  971. var inverted = currentParseScope.inverted;
  972. var ccw = bfcCCW !== inverted;
  973. var doubleSided = ! bfcCertified || ! bfcCull;
  974. var v0, v1, v2, v3, faceNormal;
  975. if ( ccw === true ) {
  976. v0 = parseVector( lp );
  977. v1 = parseVector( lp );
  978. v2 = parseVector( lp );
  979. v3 = parseVector( lp );
  980. } else {
  981. v3 = parseVector( lp );
  982. v2 = parseVector( lp );
  983. v1 = parseVector( lp );
  984. v0 = parseVector( lp );
  985. }
  986. tempVec0.subVectors( v1, v0 );
  987. tempVec1.subVectors( v2, v1 );
  988. faceNormal = new THREE.Vector3()
  989. .crossVectors( tempVec0, tempVec1 )
  990. .normalize();
  991. triangles.push( {
  992. material: material,
  993. colourCode: material.userData.code,
  994. v0: v0,
  995. v1: v1,
  996. v2: v2,
  997. faceNormal: faceNormal,
  998. n0: null,
  999. n1: null,
  1000. n2: null
  1001. } );
  1002. triangles.push( {
  1003. material: material,
  1004. colourCode: material.userData.code,
  1005. v0: v0,
  1006. v1: v2,
  1007. v2: v3,
  1008. faceNormal: faceNormal,
  1009. n0: null,
  1010. n1: null,
  1011. n2: null
  1012. } );
  1013. if ( doubleSided === true ) {
  1014. triangles.push( {
  1015. material: material,
  1016. colourCode: material.userData.code,
  1017. v0: v0,
  1018. v1: v2,
  1019. v2: v1,
  1020. faceNormal: faceNormal,
  1021. n0: null,
  1022. n1: null,
  1023. n2: null
  1024. } );
  1025. triangles.push( {
  1026. material: material,
  1027. colourCode: material.userData.code,
  1028. v0: v0,
  1029. v1: v3,
  1030. v2: v2,
  1031. faceNormal: faceNormal,
  1032. n0: null,
  1033. n1: null,
  1034. n2: null
  1035. } );
  1036. }
  1037. break;
  1038. default:
  1039. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  1040. break;
  1041. }
  1042. }
  1043. if ( parsingEmbeddedFiles ) {
  1044. this.subobjectCache[ currentEmbeddedFileName.toLowerCase() ] = currentEmbeddedText;
  1045. }
  1046. currentParseScope.category = category;
  1047. currentParseScope.keywords = keywords;
  1048. currentParseScope.subobjects = subobjects;
  1049. currentParseScope.numSubobjects = subobjects.length;
  1050. currentParseScope.subobjectIndex = 0;
  1051. },
  1052. computeConstructionSteps: function ( model ) {
  1053. // Sets userdata.constructionStep number in Group objects and userData.numConstructionSteps number in the root Group object.
  1054. var stepNumber = 0;
  1055. model.traverse( c => {
  1056. if ( c.isGroup ) {
  1057. if ( c.userData.startingConstructionStep ) {
  1058. stepNumber ++;
  1059. }
  1060. c.userData.constructionStep = stepNumber;
  1061. }
  1062. } );
  1063. model.userData.numConstructionSteps = stepNumber + 1;
  1064. },
  1065. processObject: function ( text, onProcessed, subobject, url ) {
  1066. var scope = this;
  1067. var parseScope = scope.newParseScopeLevel();
  1068. parseScope.url = url;
  1069. var parentParseScope = scope.getParentParseScope();
  1070. // Set current matrix
  1071. if ( subobject ) {
  1072. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  1073. parseScope.matrix.copy( subobject.matrix );
  1074. parseScope.inverted = subobject.inverted;
  1075. parseScope.startingConstructionStep = subobject.startingConstructionStep;
  1076. }
  1077. // Add to cache
  1078. var currentFileName = parentParseScope.currentFileName;
  1079. if ( currentFileName !== null ) {
  1080. currentFileName = parentParseScope.currentFileName.toLowerCase();
  1081. }
  1082. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  1083. scope.subobjectCache[ currentFileName ] = text;
  1084. }
  1085. // Parse the object (returns a THREE.Group)
  1086. scope.objectParse( text );
  1087. var finishedCount = 0;
  1088. onSubobjectFinish();
  1089. function onSubobjectFinish() {
  1090. finishedCount ++;
  1091. if ( finishedCount === parseScope.subobjects.length + 1 ) {
  1092. finalizeObject();
  1093. } else {
  1094. // Once the previous subobject has finished we can start processing the next one in the list.
  1095. // The subobject processing shares scope in processing so it's important that they be loaded serially
  1096. // to avoid race conditions.
  1097. // Promise.resolve is used as an approach to asynchronously schedule a task _before_ this frame ends to
  1098. // avoid stack overflow exceptions when loading many subobjects from the cache. RequestAnimationFrame
  1099. // will work but causes the load to happen after the next frame which causes the load to take significantly longer.
  1100. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  1101. Promise.resolve().then( function () {
  1102. loadSubobject( subobject );
  1103. } );
  1104. parseScope.subobjectIndex ++;
  1105. }
  1106. }
  1107. function finalizeObject() {
  1108. if ( scope.smoothNormals && parseScope.type === 'Part' ) {
  1109. smoothNormals( parseScope.triangles, parseScope.lineSegments );
  1110. }
  1111. var isRoot = ! parentParseScope.isFromParse;
  1112. if ( scope.separateObjects && ! isPrimitiveType( parseScope.type ) || isRoot ) {
  1113. const objGroup = parseScope.groupObject;
  1114. if ( parseScope.triangles.length > 0 ) {
  1115. objGroup.add( createObject( parseScope.triangles, 3 ) );
  1116. }
  1117. if ( parseScope.lineSegments.length > 0 ) {
  1118. objGroup.add( createObject( parseScope.lineSegments, 2 ) );
  1119. }
  1120. if ( parseScope.conditionalSegments.length > 0 ) {
  1121. objGroup.add( createObject( parseScope.conditionalSegments, 2, true ) );
  1122. }
  1123. if ( parentParseScope.groupObject ) {
  1124. objGroup.name = parseScope.fileName;
  1125. objGroup.userData.category = parseScope.category;
  1126. objGroup.userData.keywords = parseScope.keywords;
  1127. parseScope.matrix.decompose( objGroup.position, objGroup.quaternion, objGroup.scale );
  1128. parentParseScope.groupObject.add( objGroup );
  1129. }
  1130. } else {
  1131. var separateObjects = scope.separateObjects;
  1132. var parentLineSegments = parentParseScope.lineSegments;
  1133. var parentConditionalSegments = parentParseScope.conditionalSegments;
  1134. var parentTriangles = parentParseScope.triangles;
  1135. var lineSegments = parseScope.lineSegments;
  1136. var conditionalSegments = parseScope.conditionalSegments;
  1137. var triangles = parseScope.triangles;
  1138. for ( var i = 0, l = lineSegments.length; i < l; i ++ ) {
  1139. var ls = lineSegments[ i ];
  1140. if ( separateObjects ) {
  1141. ls.v0.applyMatrix4( parseScope.matrix );
  1142. ls.v1.applyMatrix4( parseScope.matrix );
  1143. }
  1144. parentLineSegments.push( ls );
  1145. }
  1146. for ( var i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  1147. var os = conditionalSegments[ i ];
  1148. if ( separateObjects ) {
  1149. os.v0.applyMatrix4( parseScope.matrix );
  1150. os.v1.applyMatrix4( parseScope.matrix );
  1151. os.c0.applyMatrix4( parseScope.matrix );
  1152. os.c1.applyMatrix4( parseScope.matrix );
  1153. }
  1154. parentConditionalSegments.push( os );
  1155. }
  1156. for ( var i = 0, l = triangles.length; i < l; i ++ ) {
  1157. var tri = triangles[ i ];
  1158. if ( separateObjects ) {
  1159. tri.v0 = tri.v0.clone().applyMatrix4( parseScope.matrix );
  1160. tri.v1 = tri.v1.clone().applyMatrix4( parseScope.matrix );
  1161. tri.v2 = tri.v2.clone().applyMatrix4( parseScope.matrix );
  1162. tempVec0.subVectors( tri.v1, tri.v0 );
  1163. tempVec1.subVectors( tri.v2, tri.v1 );
  1164. tri.faceNormal.crossVectors( tempVec0, tempVec1 ).normalize();
  1165. }
  1166. parentTriangles.push( tri );
  1167. }
  1168. }
  1169. scope.removeScopeLevel();
  1170. // If it is root object, compute construction steps
  1171. if ( ! parentParseScope.isFromParse ) {
  1172. scope.computeConstructionSteps( parseScope.groupObject );
  1173. }
  1174. if ( onProcessed ) {
  1175. onProcessed( parseScope.groupObject );
  1176. }
  1177. }
  1178. function loadSubobject( subobject ) {
  1179. parseScope.mainColourCode = subobject.material.userData.code;
  1180. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  1181. parseScope.currentFileName = subobject.originalFileName;
  1182. // If subobject was cached previously, use the cached one
  1183. var cached = scope.subobjectCache[ subobject.originalFileName.toLowerCase() ];
  1184. if ( cached ) {
  1185. scope.processObject( cached, function ( subobjectGroup ) {
  1186. onSubobjectLoaded( subobjectGroup, subobject );
  1187. onSubobjectFinish();
  1188. }, subobject, url );
  1189. return;
  1190. }
  1191. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  1192. // Update also subobject.locationState for the next try if this load fails.
  1193. var subobjectURL = subobject.fileName;
  1194. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  1195. switch ( subobject.locationState ) {
  1196. case LDrawLoader.FILE_LOCATION_AS_IS:
  1197. newLocationState = subobject.locationState + 1;
  1198. break;
  1199. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  1200. subobjectURL = 'parts/' + subobjectURL;
  1201. newLocationState = subobject.locationState + 1;
  1202. break;
  1203. case LDrawLoader.FILE_LOCATION_TRY_P:
  1204. subobjectURL = 'p/' + subobjectURL;
  1205. newLocationState = subobject.locationState + 1;
  1206. break;
  1207. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  1208. subobjectURL = 'models/' + subobjectURL;
  1209. newLocationState = subobject.locationState + 1;
  1210. break;
  1211. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  1212. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  1213. newLocationState = subobject.locationState + 1;
  1214. break;
  1215. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  1216. if ( subobject.triedLowerCase ) {
  1217. // Try absolute path
  1218. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  1219. } else {
  1220. // Next attempt is lower case
  1221. subobject.fileName = subobject.fileName.toLowerCase();
  1222. subobjectURL = subobject.fileName;
  1223. subobject.triedLowerCase = true;
  1224. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  1225. }
  1226. break;
  1227. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  1228. // All location possibilities have been tried, give up loading this object
  1229. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  1230. return;
  1231. }
  1232. subobject.locationState = newLocationState;
  1233. subobject.url = subobjectURL;
  1234. // Load the subobject
  1235. // Use another file loader here so we can keep track of the subobject information
  1236. // and use it when processing the next model.
  1237. var fileLoader = new THREE.FileLoader( scope.manager );
  1238. fileLoader.setPath( scope.path );
  1239. fileLoader.load( subobjectURL, function ( text ) {
  1240. scope.processObject( text, function ( subobjectGroup ) {
  1241. onSubobjectLoaded( subobjectGroup, subobject );
  1242. onSubobjectFinish();
  1243. }, subobject, url );
  1244. }, undefined, function ( err ) {
  1245. onSubobjectError( err, subobject );
  1246. }, subobject );
  1247. }
  1248. function onSubobjectLoaded( subobjectGroup, subobject ) {
  1249. if ( subobjectGroup === null ) {
  1250. // Try to reload
  1251. loadSubobject( subobject );
  1252. return;
  1253. }
  1254. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  1255. }
  1256. function onSubobjectError( err, subobject ) {
  1257. // Retry download from a different default possible location
  1258. loadSubobject( subobject );
  1259. }
  1260. }
  1261. };
  1262. return LDrawLoader;
  1263. } )();