LDrawLoader.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author yomboprime / https://github.com/yomboprime/
  4. *
  5. *
  6. */
  7. THREE.LDrawLoader = ( function () {
  8. function LineParser( line, lineNumber ) {
  9. this.line = line;
  10. this.lineLength = line.length;
  11. this.currentCharIndex = 0;
  12. this.currentChar = ' ';
  13. this.lineNumber = lineNumber;
  14. }
  15. LineParser.prototype = {
  16. constructor: LineParser,
  17. seekNonSpace: function () {
  18. while ( this.currentCharIndex < this.lineLength ) {
  19. this.currentChar = this.line.charAt( this.currentCharIndex );
  20. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  21. return;
  22. }
  23. this.currentCharIndex ++;
  24. }
  25. },
  26. getToken: function () {
  27. var pos0 = this.currentCharIndex ++;
  28. // Seek space
  29. while ( this.currentCharIndex < this.lineLength ) {
  30. this.currentChar = this.line.charAt( this.currentCharIndex );
  31. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  32. break;
  33. }
  34. this.currentCharIndex ++;
  35. }
  36. var pos1 = this.currentCharIndex;
  37. this.seekNonSpace();
  38. return this.line.substring( pos0, pos1 );
  39. },
  40. getRemainingString: function() {
  41. return this.line.substring( this.currentCharIndex, this.lineLength );
  42. },
  43. isAtTheEnd: function() {
  44. return this.currentCharIndex >= this.lineLength;
  45. },
  46. setToEnd: function () {
  47. this.currentCharIndex = this.lineLength;
  48. },
  49. getLineNumberString: function () {
  50. return this.lineNumber >= 0? " at line " + this.lineNumber: "";
  51. }
  52. };
  53. function sortByMaterial ( a, b ) {
  54. if ( a.colourCode === b.colourCode ) {
  55. return 0;
  56. }
  57. if ( a.colourCode < b.colourCode ) {
  58. return -1;
  59. }
  60. return 1;
  61. }
  62. function createObject( elements, elementSize ) {
  63. // Creates a THREE.LineSegments (elementSize = 2) or a THREE.Mesh (elementSize = 3 )
  64. // With per face / segment material, implemented with mesh groups and materials array
  65. // Sort the triangles or line segments by colour code to make later the mesh groups
  66. elements.sort( sortByMaterial );
  67. var vertices = [];
  68. var materials = [];
  69. var bufferGeometry = new THREE.BufferGeometry();
  70. bufferGeometry.clearGroups();
  71. var prevMaterial = null;
  72. var index0 = 0;
  73. var numGroupVerts = 0;
  74. for ( var iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  75. var elem = elements[ iElem ];
  76. var v0 = elem.v0;
  77. var v1 = elem.v1;
  78. // Note that LDraw coordinate system is rotated 180 deg. in the X axis w.r.t. Three.js's one
  79. vertices.push( v0.x, v0.y, v0.z, v1.x, v1.y, v1.z );
  80. if ( elementSize === 3 ) {
  81. vertices.push( elem.v2.x, elem.v2.y, elem.v2.z );
  82. }
  83. if ( prevMaterial !== elem.material ) {
  84. if ( prevMaterial !== null ) {
  85. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  86. }
  87. materials.push( elem.material );
  88. prevMaterial = elem.material;
  89. index0 = iElem * elementSize;
  90. numGroupVerts = elementSize;
  91. }
  92. else {
  93. numGroupVerts += elementSize;
  94. }
  95. }
  96. if ( numGroupVerts > 0 ) {
  97. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  98. }
  99. bufferGeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  100. var object3d = null;
  101. if ( elementSize === 2 ) {
  102. object3d = new THREE.LineSegments( bufferGeometry, materials );
  103. }
  104. else if ( elementSize === 3 ) {
  105. bufferGeometry.computeVertexNormals();
  106. object3d = new THREE.Mesh( bufferGeometry, materials );
  107. }
  108. return object3d;
  109. }
  110. //
  111. function LDrawLoader( manager ) {
  112. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  113. // This is a stack of 'parse scopes' with one level per subobject loaded file.
  114. // Each level contains a material lib and also other runtime variables passed between parent and child subobjects
  115. // When searching for a material code, the stack is read from top of the stack to bottom
  116. // Each material library is an object map keyed by colour codes.
  117. this.parseScopesStack = null;
  118. this.path = '';
  119. // Array of THREE.Material
  120. this.materials = [];
  121. // Not using THREE.Cache here because it returns the previous HTML error response instead of calling onError()
  122. // This also allows to handle the embedded text files ("0 FILE" lines)
  123. this.subobjectCache = {};
  124. // 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.
  125. this.fileMap = null;
  126. // Add default main triangle and line edge materials (used in piecess that can be coloured with a main color)
  127. this.setMaterials( [
  128. this.parseColourMetaDirective( new LineParser( "Main_Colour CODE 16 VALUE #FF8080 EDGE #333333" ) ),
  129. this.parseColourMetaDirective( new LineParser( "Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333" ) )
  130. ] );
  131. // If this flag is set to true, each subobject will be a THREE.Object.
  132. // If not (the default), only one object which contains all the merged primitives will be created.
  133. this.separateObjects = false;
  134. // Current merged object and primitives
  135. this.currentGroupObject = null;
  136. this.currentTriangles = null;
  137. this.currentLineSegments = null;
  138. }
  139. // Special surface finish tag types.
  140. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  141. LDrawLoader.FINISH_TYPE_DEFAULT = 0;
  142. LDrawLoader.FINISH_TYPE_CHROME = 1;
  143. LDrawLoader.FINISH_TYPE_PEARLESCENT = 2;
  144. LDrawLoader.FINISH_TYPE_RUBBER = 3;
  145. LDrawLoader.FINISH_TYPE_MATTE_METALLIC = 4;
  146. LDrawLoader.FINISH_TYPE_METAL = 5;
  147. // State machine to search a subobject path.
  148. // The LDraw standard establishes these various possible subfolders.
  149. LDrawLoader.FILE_LOCATION_AS_IS = 0;
  150. LDrawLoader.FILE_LOCATION_TRY_PARTS = 1;
  151. LDrawLoader.FILE_LOCATION_TRY_P = 2;
  152. LDrawLoader.FILE_LOCATION_TRY_MODELS = 3;
  153. LDrawLoader.FILE_LOCATION_TRY_RELATIVE = 4;
  154. LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE = 5;
  155. LDrawLoader.FILE_LOCATION_NOT_FOUND = 6;
  156. LDrawLoader.prototype = {
  157. constructor: LDrawLoader,
  158. load: function ( url, onLoad, onProgress, onError ) {
  159. if ( ! this.fileMap ) {
  160. this.fileMap = {};
  161. }
  162. var scope = this;
  163. var fileLoader = new THREE.FileLoader( this.manager );
  164. fileLoader.setPath( this.path );
  165. fileLoader.load( url, function( text ) {
  166. processObject( text, onLoad );
  167. }, onProgress, onError );
  168. function processObject( text, onProcessed ) {
  169. var parseScope = scope.newParseScopeLevel();
  170. parseScope.url = url;
  171. var parentParseScope = scope.getParentParseScope();
  172. // Add to cache
  173. var currentFileName = parentParseScope.currentFileName;
  174. if ( scope.subobjectCache[ currentFileName ] === undefined ) {
  175. scope.subobjectCache[ currentFileName ] = text;
  176. }
  177. // Parse the object (returns a THREE.Group)
  178. var objGroup = scope.parse( text );
  179. // Load subobjects
  180. parseScope.subobjects = objGroup.userData.subobjects;
  181. parseScope.numSubobjects = parseScope.subobjects.length;
  182. parseScope.subobjectIndex = 0;
  183. if ( parseScope.numSubobjects > 0 ) {
  184. // Load the first subobject
  185. var subobjectGroup = loadSubobject( parseScope.subobjects[ 0 ], true );
  186. // Optimization for loading pack: If subobjects are obtained from cache, keep loading them iteratively rather than recursively
  187. if ( subobjectGroup ) {
  188. while ( subobjectGroup && parseScope.subobjectIndex < parseScope.numSubobjects - 1 ) {
  189. subobjectGroup = loadSubobject( parseScope.subobjects[ ++ parseScope.subobjectIndex ], true );
  190. }
  191. if ( subobjectGroup ) {
  192. finalizeObject();
  193. }
  194. }
  195. }
  196. else {
  197. // No subobjects, finish object
  198. finalizeObject();
  199. }
  200. return objGroup;
  201. function finalizeObject() {
  202. if ( ! scope.separateObjects && ! parentParseScope.isFromParse ) {
  203. // We are finalizing the root object and merging primitives is activated, so create the entire Mesh and LineSegments objects now
  204. if ( scope.currentLineSegments.length > 0 ) {
  205. objGroup.add( createObject( scope.currentLineSegments, 2 ) );
  206. }
  207. if ( scope.currentTriangles.length > 0 ) {
  208. objGroup.add( createObject( scope.currentTriangles, 3 ) );
  209. }
  210. }
  211. scope.removeScopeLevel();
  212. if ( onProcessed ) {
  213. onProcessed( objGroup );
  214. }
  215. }
  216. function loadSubobject ( subobject, sync ) {
  217. parseScope.mainColourCode = subobject.material.userData.code;
  218. parseScope.mainEdgeColourCode = subobject.material.userData.edgeMaterial.userData.code;
  219. parseScope.currentFileName = subobject.originalFileName;
  220. if ( ! scope.separateObjects ) {
  221. // Set current matrix
  222. parseScope.currentMatrix.multiplyMatrices( parentParseScope.currentMatrix, subobject.matrix );
  223. }
  224. // If subobject was cached previously, use the cached one
  225. var cached = scope.subobjectCache[ subobject.originalFileName ];
  226. if ( cached ) {
  227. var subobjectGroup = processObject( cached, sync ? undefined : onSubobjectLoaded );
  228. if ( sync ) {
  229. addSubobject( subobject, subobjectGroup );
  230. return subobjectGroup;
  231. }
  232. return;
  233. }
  234. // Adjust file name to locate the subobject file path in standard locations (always under directory scope.path)
  235. // Update also subobject.locationState for the next try if this load fails.
  236. var subobjectURL = subobject.fileName;
  237. var newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  238. switch ( subobject.locationState ) {
  239. case LDrawLoader.FILE_LOCATION_AS_IS:
  240. newLocationState = subobject.locationState + 1;
  241. break;
  242. case LDrawLoader.FILE_LOCATION_TRY_PARTS:
  243. subobjectURL = 'parts/' + subobjectURL;
  244. newLocationState = subobject.locationState + 1;
  245. break;
  246. case LDrawLoader.FILE_LOCATION_TRY_P:
  247. subobjectURL = 'p/' + subobjectURL;
  248. newLocationState = subobject.locationState + 1;
  249. break;
  250. case LDrawLoader.FILE_LOCATION_TRY_MODELS:
  251. subobjectURL = 'models/' + subobjectURL;
  252. newLocationState = subobject.locationState + 1;
  253. break;
  254. case LDrawLoader.FILE_LOCATION_TRY_RELATIVE:
  255. subobjectURL = url.substring( 0, url.lastIndexOf( "/" ) + 1 ) + subobjectURL;
  256. newLocationState = subobject.locationState + 1;
  257. break;
  258. case LDrawLoader.FILE_LOCATION_TRY_ABSOLUTE:
  259. if ( subobject.triedLowerCase ) {
  260. // Try absolute path
  261. newLocationState = LDrawLoader.FILE_LOCATION_NOT_FOUND;
  262. }
  263. else {
  264. // Next attempt is lower case
  265. subobject.fileName = subobject.fileName.toLowerCase();
  266. subobjectURL = subobject.fileName;
  267. subobject.triedLowerCase = true;
  268. newLocationState = LDrawLoader.FILE_LOCATION_AS_IS;
  269. }
  270. break;
  271. case LDrawLoader.FILE_LOCATION_NOT_FOUND:
  272. // All location possibilities have been tried, give up loading this object
  273. console.warn( 'LDrawLoader: Subobject "' + subobject.originalFileName + '" could not be found.' );
  274. // Try to read the next subobject
  275. parseScope.subobjectIndex ++;
  276. if ( parseScope.subobjectIndex >= parseScope.numSubobjects ) {
  277. // All subojects have been loaded. Finish parent object
  278. scope.removeScopeLevel();
  279. onProcessed( objGroup );
  280. }
  281. else {
  282. // Load next subobject
  283. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  284. }
  285. return;
  286. }
  287. subobject.locationState = newLocationState;
  288. subobject.url = subobjectURL;
  289. // Load the subobject
  290. scope.load( subobjectURL, onSubobjectLoaded, undefined, onSubobjectError );
  291. }
  292. function onSubobjectLoaded( subobjectGroup ) {
  293. var subobject = parseScope.subobjects[ parseScope.subobjectIndex ];
  294. if ( subobjectGroup === null ) {
  295. // Try to reload
  296. loadSubobject( subobject );
  297. return;
  298. }
  299. // Add the subobject just loaded
  300. addSubobject( subobject, subobjectGroup );
  301. // Proceed to load the next subobject, or finish the parent object
  302. parseScope.subobjectIndex ++;
  303. if ( parseScope.subobjectIndex < parseScope.numSubobjects ) {
  304. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  305. }
  306. else {
  307. finalizeObject();
  308. }
  309. }
  310. function addSubobject ( subobject, subobjectGroup ) {
  311. if ( scope.separateObjects ) {
  312. subobjectGroup.name = subobject.fileName;
  313. objGroup.add( subobjectGroup );
  314. subobjectGroup.matrix.copy( subobject.matrix );
  315. subobjectGroup.matrixAutoUpdate = false;
  316. }
  317. scope.fileMap[ subobject.originalFileName ] = subobject.url;
  318. }
  319. function onSubobjectError( err ) {
  320. // Retry download from a different default possible location
  321. loadSubobject( parseScope.subobjects[ parseScope.subobjectIndex ] );
  322. }
  323. }
  324. },
  325. setPath: function ( value ) {
  326. this.path = value;
  327. return this;
  328. },
  329. setMaterials: function ( materials ) {
  330. // Clears parse scopes stack, adds new scope with material library
  331. this.parseScopesStack = [];
  332. this.newParseScopeLevel( materials );
  333. this.getCurrentParseScope().isFromParse = false;
  334. this.materials = materials;
  335. this.currentGroupObject = null;
  336. return this;
  337. },
  338. setFileMap: function( fileMap ) {
  339. this.fileMap = fileMap;
  340. return this;
  341. },
  342. newParseScopeLevel: function ( materials ) {
  343. // Adds a new scope level, assign materials to it and returns it
  344. var matLib = {};
  345. if ( materials ) {
  346. for ( var i = 0, n = materials.length; i < n; i ++ ) {
  347. var material = materials[ i ];
  348. matLib[ material.userData.code ] = material;
  349. }
  350. }
  351. var topParseScope = this.getCurrentParseScope();
  352. var parentParseScope = this.getParentParseScope();
  353. var newParseScope = {
  354. lib: matLib,
  355. url: null,
  356. // Subobjects
  357. subobjects: null,
  358. numSubobjects: 0,
  359. subobjectIndex: 0,
  360. // Current subobject
  361. currentFileName: null,
  362. mainColourCode: topParseScope ? topParseScope.mainColourCode : '16',
  363. mainEdgeColourCode: topParseScope ? topParseScope.mainEdgeColourCode : '24',
  364. currentMatrix: new THREE.Matrix4(),
  365. // If false, it is a root material scope previous to parse
  366. isFromParse: true
  367. };
  368. this.parseScopesStack.push( newParseScope );
  369. return newParseScope;
  370. },
  371. removeScopeLevel: function() {
  372. this.parseScopesStack.pop();
  373. return this;
  374. },
  375. addMaterial: function ( material ) {
  376. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  377. var matLib = this.getCurrentParseScope().lib;
  378. if ( ! matLib[ material.userData.code ] ) {
  379. this.materials.push( material );
  380. }
  381. matLib[ material.userData.code ] = material;
  382. return this;
  383. },
  384. getMaterial: function ( colourCode ) {
  385. // Given a colour code search its material in the parse scopes stack
  386. if ( colourCode.startsWith( "0x2" ) ) {
  387. // Special 'direct' material value (RGB colour)
  388. var colour = colourCode.substring( 3 );
  389. return this.parseColourMetaDirective( new LineParser( "Direct_Color_" + colour + " CODE -1 VALUE #" + colour + " EDGE #" + colour + "" ) );
  390. }
  391. for ( var i = this.parseScopesStack.length - 1; i >= 0; i-- ) {
  392. var material = this.parseScopesStack[ i ].lib[ colourCode ];
  393. if ( material ) {
  394. return material;
  395. }
  396. }
  397. // Material was not found
  398. return null;
  399. },
  400. getParentParseScope: function () {
  401. if ( this.parseScopesStack.length > 1 ) {
  402. return this.parseScopesStack[ this.parseScopesStack.length - 2 ];
  403. }
  404. return null;
  405. },
  406. getCurrentParseScope: function () {
  407. if ( this.parseScopesStack.length > 0 ) {
  408. return this.parseScopesStack[ this.parseScopesStack.length - 1 ];
  409. }
  410. return null;
  411. },
  412. parseColourMetaDirective: function ( lineParser ) {
  413. // Parses a colour definition and returns a THREE.Material or null if error
  414. var code = null;
  415. // Triangle and line colours
  416. var colour = 0xFF00FF;
  417. var edgeColour = 0xFF00FF;
  418. // Transparency
  419. var alpha = 1;
  420. var isTransparent = false;
  421. // Self-illumination:
  422. var luminance = 0;
  423. var finishType = LDrawLoader.FINISH_TYPE_DEFAULT;
  424. var canHaveEnvMap = true;
  425. var edgeMaterial = null;
  426. var name = lineParser.getToken();
  427. if ( ! name ) {
  428. throw 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + ".";
  429. }
  430. // Parse tag tokens and their parameters
  431. var token = null;
  432. while ( true ) {
  433. token = lineParser.getToken();
  434. if ( ! token ) {
  435. break;
  436. }
  437. switch ( token.toUpperCase() ) {
  438. case "CODE":
  439. code = lineParser.getToken();
  440. break;
  441. case "VALUE":
  442. colour = lineParser.getToken();
  443. if ( colour.startsWith( '0x' ) ) {
  444. colour = '#' + colour.substring( 2 );
  445. }
  446. else if ( ! colour.startsWith( '#' ) ) {
  447. throw 'LDrawLoader: Invalid colour while parsing material' + lineParser.getLineNumberString() + ".";
  448. }
  449. break;
  450. case "EDGE":
  451. edgeColour = lineParser.getToken();
  452. if ( edgeColour.startsWith( '0x' ) ) {
  453. edgeColour = '#' + edgeColour.substring( 2 );
  454. }
  455. else if ( ! edgeColour.startsWith( '#' ) ) {
  456. // Try to see if edge colour is a colour code
  457. edgeMaterial = this.getMaterial( edgeColour );
  458. if ( ! edgeMaterial ) {
  459. throw 'LDrawLoader: Invalid edge colour while parsing material' + lineParser.getLineNumberString() + ".";
  460. }
  461. // Get the edge material for this triangle material
  462. edgeMaterial = edgeMaterial.userData.edgeMaterial;
  463. }
  464. break;
  465. case 'ALPHA':
  466. alpha = parseInt( lineParser.getToken() );
  467. if ( isNaN( alpha ) ) {
  468. throw 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + ".";
  469. }
  470. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  471. if ( alpha < 1 ) {
  472. isTransparent = true;
  473. }
  474. break;
  475. case 'LUMINANCE':
  476. luminance = parseInt( lineParser.getToken() );
  477. if ( isNaN( luminance ) ) {
  478. throw 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + ".";
  479. }
  480. luminance = Math.max( 0, Math.min( 1, luminance / 255 ) );
  481. break;
  482. case 'CHROME':
  483. finishType = LDrawLoader.FINISH_TYPE_CHROME;
  484. break;
  485. case 'PEARLESCENT':
  486. finishType = LDrawLoader.FINISH_TYPE_PEARLESCENT;
  487. break;
  488. case 'RUBBER':
  489. finishType = LDrawLoader.FINISH_TYPE_RUBBER;
  490. break;
  491. case 'MATTE_METALLIC':
  492. finishType = LDrawLoader.FINISH_TYPE_MATTE_METALLIC;
  493. break;
  494. case 'METAL':
  495. finishType = LDrawLoader.FINISH_TYPE_METAL;
  496. break;
  497. case 'MATERIAL':
  498. // Not implemented
  499. lineParser.setToEnd();
  500. break;
  501. default:
  502. throw 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + ".";
  503. break;
  504. }
  505. }
  506. var material = null;
  507. switch ( finishType ) {
  508. case LDrawLoader.FINISH_TYPE_DEFAULT:
  509. case LDrawLoader.FINISH_TYPE_PEARLESCENT:
  510. var specular = new THREE.Color( colour );
  511. var shininess = 35;
  512. var hsl = specular.getHSL( { h: 0, s: 0, l: 0 } );
  513. if ( finishType === LDrawLoader.FINISH_TYPE_DEFAULT ) {
  514. // Default plastic material with shiny specular
  515. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.12 );
  516. }
  517. else {
  518. // Try to imitate pearlescency by setting the specular to the complementary of the color, and low shininess
  519. hsl.h = ( hsl.h + 0.5 ) % 1;
  520. hsl.l = Math.min( 1, hsl.l + ( 1 - hsl.l ) * 0.7 );
  521. shininess = 10;
  522. }
  523. specular.setHSL( hsl.h, hsl.s, hsl.l );
  524. material = new THREE.MeshPhongMaterial( { color: colour, specular: specular, shininess: shininess, reflectivity: 0.3 } );
  525. break;
  526. case LDrawLoader.FINISH_TYPE_CHROME:
  527. // Mirror finish surface
  528. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0, metalness: 1 } );
  529. break;
  530. case LDrawLoader.FINISH_TYPE_RUBBER:
  531. // Rubber is best simulated with Lambert
  532. material = new THREE.MeshLambertMaterial( { color: colour } );
  533. canHaveEnvMap = false;
  534. break;
  535. case LDrawLoader.FINISH_TYPE_MATTE_METALLIC:
  536. // Brushed metal finish
  537. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.8, metalness: 0.4 } );
  538. break;
  539. case LDrawLoader.FINISH_TYPE_METAL:
  540. // Average metal finish
  541. material = new THREE.MeshStandardMaterial( { color: colour, roughness: 0.2, metalness: 0.85 } );
  542. break;
  543. default:
  544. // Should not happen
  545. break;
  546. }
  547. // BFC (Back Face Culling) LDraw language meta extension is not implemented, so set all materials double-sided:
  548. material.side = THREE.DoubleSide;
  549. material.transparent = isTransparent;
  550. material.opacity = alpha;
  551. material.userData.canHaveEnvMap = canHaveEnvMap;
  552. if ( luminance !== 0 ) {
  553. material.emissive.set( material.color ).multiplyScalar( luminance );
  554. }
  555. if ( ! edgeMaterial ) {
  556. // This is the material used for edges
  557. edgeMaterial = new THREE.LineBasicMaterial( { color: edgeColour } );
  558. edgeMaterial.userData.code = code;
  559. edgeMaterial.name = name + " - Edge";
  560. edgeMaterial.userData.canHaveEnvMap = false;
  561. }
  562. material.userData.code = code;
  563. material.name = name;
  564. material.userData.edgeMaterial = edgeMaterial;
  565. return material;
  566. },
  567. //
  568. parse: function ( text ) {
  569. //console.time( 'LDrawLoader' );
  570. // Retrieve data from the parent parse scope
  571. var parentParseScope = this.getParentParseScope();
  572. // Main colour codes passed to this subobject (or default codes 16 and 24 if it is the root object)
  573. var mainColourCode = parentParseScope.mainColourCode;
  574. var mainEdgeColourCode = parentParseScope.mainEdgeColourCode;
  575. var url = parentParseScope.url;
  576. var currentParseScope = this.getCurrentParseScope();
  577. // Parse result variables
  578. var triangles;
  579. var lineSegments;
  580. if ( this.separateObjects ) {
  581. triangles = [];
  582. lineSegments = [];
  583. }
  584. else {
  585. if ( this.currentGroupObject === null ) {
  586. this.currentGroupObject = new THREE.Group();
  587. this.currentTriangles = [];
  588. this.currentLineSegments = [];
  589. }
  590. triangles = this.currentTriangles;
  591. lineSegments = this.currentLineSegments;
  592. }
  593. var subobjects = [];
  594. var category = null;
  595. var keywords = null;
  596. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  597. // This is faster than String.split with regex that splits on both
  598. text = text.replace( /\r\n/g, '\n' );
  599. }
  600. var lines = text.split( '\n' );
  601. var numLines = lines.length;
  602. var lineIndex = 0;
  603. var parsingEmbeddedFiles = false;
  604. var currentEmbeddedFileName = null;
  605. var currentEmbeddedText = null;
  606. var scope = this;
  607. function parseColourCode( lineParser, forEdge ) {
  608. // Parses next colour code and returns a THREE.Material
  609. var colourCode = lineParser.getToken();
  610. if ( ! forEdge && colourCode === '16' ) {
  611. colourCode = mainColourCode;
  612. }
  613. if ( forEdge && colourCode === '24' ) {
  614. colourCode = mainEdgeColourCode;
  615. }
  616. var material = scope.getMaterial( colourCode );
  617. if ( ! material ) {
  618. throw 'LDrawLoader: Unknown colour code "' + colourCode + '" is used' + lineParser.getLineNumberString() + ' but it was not defined previously.';
  619. }
  620. return material;
  621. }
  622. function parseVector ( lp ) {
  623. var v = new THREE.Vector3( parseFloat( lp.getToken() ), parseFloat( lp.getToken() ), parseFloat( lp.getToken() ) );
  624. if ( ! scope.separateObjects ) {
  625. v.applyMatrix4( parentParseScope.currentMatrix );
  626. }
  627. return v;
  628. }
  629. function findSubobject( fileName ) {
  630. for ( var i = 0, n = subobjects.length; i < n; i ++ ) {
  631. if ( subobjects[ i ].fileName === fileName ) {
  632. return subobjects[ i ];
  633. }
  634. return null;
  635. }
  636. }
  637. // Parse all line commands
  638. for ( lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  639. line = lines[ lineIndex ];
  640. if ( line.length === 0 ) continue;
  641. if ( parsingEmbeddedFiles ) {
  642. if ( line.startsWith( '0 FILE ' ) ) {
  643. // Save previous embedded file in the cache
  644. this.subobjectCache[ currentEmbeddedFileName ] = currentEmbeddedText;
  645. // New embedded text file
  646. currentEmbeddedFileName = line.substring( 7 );
  647. currentEmbeddedText = '';
  648. }
  649. else {
  650. currentEmbeddedText += line + '\n';
  651. }
  652. continue;
  653. }
  654. var lp = new LineParser( line, lineIndex + 1 );
  655. lp.seekNonSpace();
  656. if ( lp.isAtTheEnd() ) {
  657. // Empty line
  658. continue;
  659. }
  660. // Parse the line type
  661. var lineType = lp.getToken();
  662. switch ( lineType ) {
  663. // Line type 0: Comment or META
  664. case '0':
  665. // Parse meta directive
  666. var meta = lp.getToken();
  667. if ( meta ) {
  668. switch ( meta ) {
  669. case '!COLOUR':
  670. var material = this.parseColourMetaDirective( lp );
  671. if ( material ) {
  672. this.addMaterial( material );
  673. }
  674. else {
  675. console.warn( 'LDrawLoader: Error parsing material' + lineParser.getLineNumberString() );
  676. }
  677. break;
  678. case '!CATEGORY':
  679. category = lp.getToken();
  680. break;
  681. case '!KEYWORDS':
  682. var newKeywords = lp.getRemainingString().split( ',' );
  683. if ( newKeywords.length > 0 ) {
  684. if ( ! keywords ) {
  685. keywords = [];
  686. }
  687. newKeywords.forEach( function( keyword ) {
  688. keywords.push( keyword.trim() );
  689. } );
  690. }
  691. break;
  692. case 'FILE':
  693. if ( lineIndex > 0 ) {
  694. // Start embedded text files parsing
  695. parsingEmbeddedFiles = true;
  696. currentEmbeddedFileName = lp.getRemainingString();
  697. currentEmbeddedText = '';
  698. }
  699. break;
  700. default:
  701. // Other meta directives are not implemented
  702. break;
  703. }
  704. }
  705. break;
  706. // Line type 1: Sub-object file
  707. case '1':
  708. var material = parseColourCode( lp );
  709. var posX = parseFloat( lp.getToken() );
  710. var posY = parseFloat( lp.getToken() );
  711. var posZ = parseFloat( lp.getToken() );
  712. var m0 = parseFloat( lp.getToken() );
  713. var m1 = parseFloat( lp.getToken() );
  714. var m2 = parseFloat( lp.getToken() );
  715. var m3 = parseFloat( lp.getToken() );
  716. var m4 = parseFloat( lp.getToken() );
  717. var m5 = parseFloat( lp.getToken() );
  718. var m6 = parseFloat( lp.getToken() );
  719. var m7 = parseFloat( lp.getToken() );
  720. var m8 = parseFloat( lp.getToken() );
  721. var matrix = new THREE.Matrix4().set(
  722. m0, m1, m2, posX,
  723. m3, m4, m5, posY,
  724. m6, m7, m8, posZ,
  725. 0, 0, 0, 1
  726. );
  727. var fileName = lp.getRemainingString().trim().replace( "\\", "/" );
  728. if ( scope.fileMap[ fileName ] ) {
  729. // Found the subobject path in the preloaded file path map
  730. fileName = scope.fileMap[ fileName ];
  731. }
  732. else {
  733. // Standardized subfolders
  734. if ( fileName.startsWith( 's/' ) ) {
  735. fileName = 'parts/' + fileName;
  736. }
  737. else if ( fileName.startsWith( '48/' ) ) {
  738. fileName = 'p/' + fileName;
  739. }
  740. }
  741. subobjects.push( {
  742. material: material,
  743. matrix: matrix,
  744. fileName: fileName,
  745. originalFileName: fileName,
  746. locationState: LDrawLoader.FILE_LOCATION_AS_IS,
  747. url: null,
  748. triedLowerCase: false
  749. } );
  750. break;
  751. // Line type 2: Line segment
  752. case '2':
  753. var material = parseColourCode( lp, true );
  754. lineSegments.push( {
  755. material: material.userData.edgeMaterial,
  756. colourCode: material.userData.code,
  757. v0: parseVector( lp ),
  758. v1: parseVector( lp )
  759. } );
  760. break;
  761. // Line type 3: Triangle
  762. case '3':
  763. var material = parseColourCode( lp );
  764. triangles.push( {
  765. material: material,
  766. colourCode: material.userData.code,
  767. v0: parseVector( lp ),
  768. v1: parseVector( lp ),
  769. v2: parseVector( lp )
  770. } );
  771. break;
  772. // Line type 4: Quadrilateral
  773. case '4':
  774. var material = parseColourCode( lp );
  775. var v0 = parseVector( lp );
  776. var v1 = parseVector( lp );
  777. var v2 = parseVector( lp );
  778. var v3 = parseVector( lp );
  779. triangles.push( {
  780. material: material,
  781. colourCode: material.userData.code,
  782. v0: v0,
  783. v1: v1,
  784. v2: v2
  785. } );
  786. triangles.push( {
  787. material: material,
  788. colourCode: material.userData.code,
  789. v0: v0,
  790. v1: v2,
  791. v2: v3
  792. } );
  793. break;
  794. // Line type 5: Optional line
  795. case '5':
  796. // Line type 5 is not implemented
  797. break;
  798. default:
  799. throw 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.';
  800. break;
  801. }
  802. }
  803. if ( parsingEmbeddedFiles ) {
  804. this.subobjectCache[ currentEmbeddedFileName ] = currentEmbeddedText;
  805. }
  806. //
  807. var groupObject = null;
  808. if ( this.separateObjects ) {
  809. groupObject = new THREE.Group();
  810. if ( lineSegments.length > 0 ) {
  811. groupObject.add( createObject( lineSegments, 2 ) );
  812. }
  813. if ( triangles.length > 0 ) {
  814. groupObject.add( createObject( triangles, 3 ) );
  815. }
  816. }
  817. else {
  818. groupObject = this.currentGroupObject;
  819. }
  820. groupObject.userData.category = category;
  821. groupObject.userData.keywords = keywords;
  822. groupObject.userData.subobjects = subobjects;
  823. //console.timeEnd( 'LDrawLoader' );
  824. return groupObject;
  825. }
  826. };
  827. return LDrawLoader;
  828. } )();