LDrawLoader.js 33 KB

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