LDrawLoader.js 32 KB

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