LDrawLoader.js 45 KB

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