LDrawLoader.js 44 KB

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