LDrawLoader.js 46 KB

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