LDrawLoader.js 43 KB

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