LDrawLoader.js 33 KB

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