LDrawLoader.js 46 KB

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