2
0

LDrawLoader.js 44 KB

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