LDrawLoader.js 31 KB

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