LDrawLoader.js 44 KB

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