LDrawLoader.js 45 KB

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