LDrawLoader.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. Color,
  5. FileLoader,
  6. Group,
  7. LineBasicMaterial,
  8. LineSegments,
  9. Loader,
  10. Matrix4,
  11. Mesh,
  12. MeshStandardMaterial,
  13. SRGBColorSpace,
  14. Vector3,
  15. Ray
  16. } from 'three';
  17. // Special surface finish tag types.
  18. // Note: "MATERIAL" tag (e.g. GLITTER, SPECKLE) is not implemented
  19. const FINISH_TYPE_DEFAULT = 0;
  20. const FINISH_TYPE_CHROME = 1;
  21. const FINISH_TYPE_PEARLESCENT = 2;
  22. const FINISH_TYPE_RUBBER = 3;
  23. const FINISH_TYPE_MATTE_METALLIC = 4;
  24. const FINISH_TYPE_METAL = 5;
  25. // State machine to search a subobject path.
  26. // The LDraw standard establishes these various possible subfolders.
  27. const FILE_LOCATION_TRY_PARTS = 0;
  28. const FILE_LOCATION_TRY_P = 1;
  29. const FILE_LOCATION_TRY_MODELS = 2;
  30. const FILE_LOCATION_AS_IS = 3;
  31. const FILE_LOCATION_TRY_RELATIVE = 4;
  32. const FILE_LOCATION_TRY_ABSOLUTE = 5;
  33. const FILE_LOCATION_NOT_FOUND = 6;
  34. const MAIN_COLOUR_CODE = '16';
  35. const MAIN_EDGE_COLOUR_CODE = '24';
  36. const COLOR_SPACE_LDRAW = SRGBColorSpace;
  37. const _tempVec0 = new Vector3();
  38. const _tempVec1 = new Vector3();
  39. class ConditionalLineSegments extends LineSegments {
  40. constructor( geometry, material ) {
  41. super( geometry, material );
  42. this.isConditionalLine = true;
  43. }
  44. }
  45. function generateFaceNormals( faces ) {
  46. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  47. const face = faces[ i ];
  48. const vertices = face.vertices;
  49. const v0 = vertices[ 0 ];
  50. const v1 = vertices[ 1 ];
  51. const v2 = vertices[ 2 ];
  52. _tempVec0.subVectors( v1, v0 );
  53. _tempVec1.subVectors( v2, v1 );
  54. face.faceNormal = new Vector3()
  55. .crossVectors( _tempVec0, _tempVec1 )
  56. .normalize();
  57. }
  58. }
  59. const _ray = new Ray();
  60. function smoothNormals( faces, lineSegments, checkSubSegments = false ) {
  61. // NOTE: 1e2 is pretty coarse but was chosen to quantize the resulting value because
  62. // it allows edges to be smoothed as expected (see minifig arms).
  63. // --
  64. // And the vector values are initialize multiplied by 1 + 1e-10 to account for floating
  65. // point errors on vertices along quantization boundaries. Ie after matrix multiplication
  66. // vertices that should be merged might be set to "1.7" and "1.6999..." meaning they won't
  67. // get merged. This added epsilon attempts to push these error values to the same quantized
  68. // value for the sake of hashing. See "AT-ST mini" dishes. See mrdoob/three#23169.
  69. const hashMultiplier = ( 1 + 1e-10 ) * 1e2;
  70. function hashVertex( v ) {
  71. const x = ~ ~ ( v.x * hashMultiplier );
  72. const y = ~ ~ ( v.y * hashMultiplier );
  73. const z = ~ ~ ( v.z * hashMultiplier );
  74. return `${ x },${ y },${ z }`;
  75. }
  76. function hashEdge( v0, v1 ) {
  77. return `${ hashVertex( v0 ) }_${ hashVertex( v1 ) }`;
  78. }
  79. // converts the two vertices to a ray with a normalized direction and origin of 0, 0, 0 projected
  80. // onto the original line.
  81. function toNormalizedRay( v0, v1, targetRay ) {
  82. targetRay.direction.subVectors( v1, v0 ).normalize();
  83. const scalar = v0.dot( targetRay.direction );
  84. targetRay.origin.copy( v0 ).addScaledVector( targetRay.direction, - scalar );
  85. return targetRay;
  86. }
  87. function hashRay( ray ) {
  88. return hashEdge( ray.origin, ray.direction );
  89. }
  90. const hardEdges = new Set();
  91. const hardEdgeRays = new Map();
  92. const halfEdgeList = {};
  93. const normals = [];
  94. // Save the list of hard edges by hash
  95. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  96. const ls = lineSegments[ i ];
  97. const vertices = ls.vertices;
  98. const v0 = vertices[ 0 ];
  99. const v1 = vertices[ 1 ];
  100. hardEdges.add( hashEdge( v0, v1 ) );
  101. hardEdges.add( hashEdge( v1, v0 ) );
  102. // only generate the hard edge ray map if we're checking subsegments because it's more expensive to check
  103. // and requires more memory.
  104. if ( checkSubSegments ) {
  105. // add both ray directions to the map
  106. const ray = toNormalizedRay( v0, v1, new Ray() );
  107. const rh1 = hashRay( ray );
  108. if ( ! hardEdgeRays.has( rh1 ) ) {
  109. toNormalizedRay( v1, v0, ray );
  110. const rh2 = hashRay( ray );
  111. const info = {
  112. ray,
  113. distances: [],
  114. };
  115. hardEdgeRays.set( rh1, info );
  116. hardEdgeRays.set( rh2, info );
  117. }
  118. // store both segments ends in min, max order in the distances array to check if a face edge is a
  119. // subsegment later.
  120. const info = hardEdgeRays.get( rh1 );
  121. let d0 = info.ray.direction.dot( v0 );
  122. let d1 = info.ray.direction.dot( v1 );
  123. if ( d0 > d1 ) {
  124. [ d0, d1 ] = [ d1, d0 ];
  125. }
  126. info.distances.push( d0, d1 );
  127. }
  128. }
  129. // track the half edges associated with each triangle
  130. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  131. const tri = faces[ i ];
  132. const vertices = tri.vertices;
  133. const vertCount = vertices.length;
  134. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  135. const index = i2;
  136. const next = ( i2 + 1 ) % vertCount;
  137. const v0 = vertices[ index ];
  138. const v1 = vertices[ next ];
  139. const hash = hashEdge( v0, v1 );
  140. // don't add the triangle if the edge is supposed to be hard
  141. if ( hardEdges.has( hash ) ) {
  142. continue;
  143. }
  144. // if checking subsegments then check to see if this edge lies on a hard edge ray and whether its within any ray bounds
  145. if ( checkSubSegments ) {
  146. toNormalizedRay( v0, v1, _ray );
  147. const rayHash = hashRay( _ray );
  148. if ( hardEdgeRays.has( rayHash ) ) {
  149. const info = hardEdgeRays.get( rayHash );
  150. const { ray, distances } = info;
  151. let d0 = ray.direction.dot( v0 );
  152. let d1 = ray.direction.dot( v1 );
  153. if ( d0 > d1 ) {
  154. [ d0, d1 ] = [ d1, d0 ];
  155. }
  156. // return early if the face edge is found to be a subsegment of a line edge meaning the edge will have "hard" normals
  157. let found = false;
  158. for ( let i = 0, l = distances.length; i < l; i += 2 ) {
  159. if ( d0 >= distances[ i ] && d1 <= distances[ i + 1 ] ) {
  160. found = true;
  161. break;
  162. }
  163. }
  164. if ( found ) {
  165. continue;
  166. }
  167. }
  168. }
  169. const info = {
  170. index: index,
  171. tri: tri
  172. };
  173. halfEdgeList[ hash ] = info;
  174. }
  175. }
  176. // Iterate until we've tried to connect all faces to share normals
  177. while ( true ) {
  178. // Stop if there are no more faces left
  179. let halfEdge = null;
  180. for ( const key in halfEdgeList ) {
  181. halfEdge = halfEdgeList[ key ];
  182. break;
  183. }
  184. if ( halfEdge === null ) {
  185. break;
  186. }
  187. // Exhaustively find all connected faces
  188. const queue = [ halfEdge ];
  189. while ( queue.length > 0 ) {
  190. // initialize all vertex normals in this triangle
  191. const tri = queue.pop().tri;
  192. const vertices = tri.vertices;
  193. const vertNormals = tri.normals;
  194. const faceNormal = tri.faceNormal;
  195. // Check if any edge is connected to another triangle edge
  196. const vertCount = vertices.length;
  197. for ( let i2 = 0; i2 < vertCount; i2 ++ ) {
  198. const index = i2;
  199. const next = ( i2 + 1 ) % vertCount;
  200. const v0 = vertices[ index ];
  201. const v1 = vertices[ next ];
  202. // delete this triangle from the list so it won't be found again
  203. const hash = hashEdge( v0, v1 );
  204. delete halfEdgeList[ hash ];
  205. const reverseHash = hashEdge( v1, v0 );
  206. const otherInfo = halfEdgeList[ reverseHash ];
  207. if ( otherInfo ) {
  208. const otherTri = otherInfo.tri;
  209. const otherIndex = otherInfo.index;
  210. const otherNormals = otherTri.normals;
  211. const otherVertCount = otherNormals.length;
  212. const otherFaceNormal = otherTri.faceNormal;
  213. // NOTE: If the angle between faces is > 67.5 degrees then assume it's
  214. // hard edge. There are some cases where the line segments do not line up exactly
  215. // with or span multiple triangle edges (see Lunar Vehicle wheels).
  216. if ( Math.abs( otherTri.faceNormal.dot( tri.faceNormal ) ) < 0.25 ) {
  217. continue;
  218. }
  219. // if this triangle has already been traversed then it won't be in
  220. // the halfEdgeList. If it has not then add it to the queue and delete
  221. // it so it won't be found again.
  222. if ( reverseHash in halfEdgeList ) {
  223. queue.push( otherInfo );
  224. delete halfEdgeList[ reverseHash ];
  225. }
  226. // share the first normal
  227. const otherNext = ( otherIndex + 1 ) % otherVertCount;
  228. if (
  229. vertNormals[ index ] && otherNormals[ otherNext ] &&
  230. vertNormals[ index ] !== otherNormals[ otherNext ]
  231. ) {
  232. otherNormals[ otherNext ].norm.add( vertNormals[ index ].norm );
  233. vertNormals[ index ].norm = otherNormals[ otherNext ].norm;
  234. }
  235. let sharedNormal1 = vertNormals[ index ] || otherNormals[ otherNext ];
  236. if ( sharedNormal1 === null ) {
  237. // it's possible to encounter an edge of a triangle that has already been traversed meaning
  238. // both edges already have different normals defined and shared. To work around this we create
  239. // a wrapper object so when those edges are merged the normals can be updated everywhere.
  240. sharedNormal1 = { norm: new Vector3() };
  241. normals.push( sharedNormal1.norm );
  242. }
  243. if ( vertNormals[ index ] === null ) {
  244. vertNormals[ index ] = sharedNormal1;
  245. sharedNormal1.norm.add( faceNormal );
  246. }
  247. if ( otherNormals[ otherNext ] === null ) {
  248. otherNormals[ otherNext ] = sharedNormal1;
  249. sharedNormal1.norm.add( otherFaceNormal );
  250. }
  251. // share the second normal
  252. if (
  253. vertNormals[ next ] && otherNormals[ otherIndex ] &&
  254. vertNormals[ next ] !== otherNormals[ otherIndex ]
  255. ) {
  256. otherNormals[ otherIndex ].norm.add( vertNormals[ next ].norm );
  257. vertNormals[ next ].norm = otherNormals[ otherIndex ].norm;
  258. }
  259. let sharedNormal2 = vertNormals[ next ] || otherNormals[ otherIndex ];
  260. if ( sharedNormal2 === null ) {
  261. sharedNormal2 = { norm: new Vector3() };
  262. normals.push( sharedNormal2.norm );
  263. }
  264. if ( vertNormals[ next ] === null ) {
  265. vertNormals[ next ] = sharedNormal2;
  266. sharedNormal2.norm.add( faceNormal );
  267. }
  268. if ( otherNormals[ otherIndex ] === null ) {
  269. otherNormals[ otherIndex ] = sharedNormal2;
  270. sharedNormal2.norm.add( otherFaceNormal );
  271. }
  272. }
  273. }
  274. }
  275. }
  276. // The normals of each face have been added up so now we average them by normalizing the vector.
  277. for ( let i = 0, l = normals.length; i < l; i ++ ) {
  278. normals[ i ].normalize();
  279. }
  280. }
  281. function isPartType( type ) {
  282. return type === 'Part' || type === 'Unofficial_Part';
  283. }
  284. function isPrimitiveType( type ) {
  285. return /primitive/i.test( type ) || type === 'Subpart';
  286. }
  287. class LineParser {
  288. constructor( line, lineNumber ) {
  289. this.line = line;
  290. this.lineLength = line.length;
  291. this.currentCharIndex = 0;
  292. this.currentChar = ' ';
  293. this.lineNumber = lineNumber;
  294. }
  295. seekNonSpace() {
  296. while ( this.currentCharIndex < this.lineLength ) {
  297. this.currentChar = this.line.charAt( this.currentCharIndex );
  298. if ( this.currentChar !== ' ' && this.currentChar !== '\t' ) {
  299. return;
  300. }
  301. this.currentCharIndex ++;
  302. }
  303. }
  304. getToken() {
  305. const pos0 = this.currentCharIndex ++;
  306. // Seek space
  307. while ( this.currentCharIndex < this.lineLength ) {
  308. this.currentChar = this.line.charAt( this.currentCharIndex );
  309. if ( this.currentChar === ' ' || this.currentChar === '\t' ) {
  310. break;
  311. }
  312. this.currentCharIndex ++;
  313. }
  314. const pos1 = this.currentCharIndex;
  315. this.seekNonSpace();
  316. return this.line.substring( pos0, pos1 );
  317. }
  318. getVector() {
  319. return new Vector3( parseFloat( this.getToken() ), parseFloat( this.getToken() ), parseFloat( this.getToken() ) );
  320. }
  321. getRemainingString() {
  322. return this.line.substring( this.currentCharIndex, this.lineLength );
  323. }
  324. isAtTheEnd() {
  325. return this.currentCharIndex >= this.lineLength;
  326. }
  327. setToEnd() {
  328. this.currentCharIndex = this.lineLength;
  329. }
  330. getLineNumberString() {
  331. return this.lineNumber >= 0 ? ' at line ' + this.lineNumber : '';
  332. }
  333. }
  334. // Fetches and parses an intermediate representation of LDraw parts files.
  335. class LDrawParsedCache {
  336. constructor( loader ) {
  337. this.loader = loader;
  338. this._cache = {};
  339. }
  340. cloneResult( original ) {
  341. const result = {};
  342. // vertices are transformed and normals computed before being converted to geometry
  343. // so these pieces must be cloned.
  344. result.faces = original.faces.map( face => {
  345. return {
  346. colorCode: face.colorCode,
  347. material: face.material,
  348. vertices: face.vertices.map( v => v.clone() ),
  349. normals: face.normals.map( () => null ),
  350. faceNormal: null
  351. };
  352. } );
  353. result.conditionalSegments = original.conditionalSegments.map( face => {
  354. return {
  355. colorCode: face.colorCode,
  356. material: face.material,
  357. vertices: face.vertices.map( v => v.clone() ),
  358. controlPoints: face.controlPoints.map( v => v.clone() )
  359. };
  360. } );
  361. result.lineSegments = original.lineSegments.map( face => {
  362. return {
  363. colorCode: face.colorCode,
  364. material: face.material,
  365. vertices: face.vertices.map( v => v.clone() )
  366. };
  367. } );
  368. // none if this is subsequently modified
  369. result.type = original.type;
  370. result.category = original.category;
  371. result.keywords = original.keywords;
  372. result.author = original.author;
  373. result.subobjects = original.subobjects;
  374. result.fileName = original.fileName;
  375. result.totalFaces = original.totalFaces;
  376. result.startingBuildingStep = original.startingBuildingStep;
  377. result.materials = original.materials;
  378. result.group = null;
  379. return result;
  380. }
  381. async fetchData( fileName ) {
  382. let triedLowerCase = false;
  383. let locationState = FILE_LOCATION_TRY_PARTS;
  384. while ( locationState !== FILE_LOCATION_NOT_FOUND ) {
  385. let subobjectURL = fileName;
  386. switch ( locationState ) {
  387. case FILE_LOCATION_AS_IS:
  388. locationState = locationState + 1;
  389. break;
  390. case FILE_LOCATION_TRY_PARTS:
  391. subobjectURL = 'parts/' + subobjectURL;
  392. locationState = locationState + 1;
  393. break;
  394. case FILE_LOCATION_TRY_P:
  395. subobjectURL = 'p/' + subobjectURL;
  396. locationState = locationState + 1;
  397. break;
  398. case FILE_LOCATION_TRY_MODELS:
  399. subobjectURL = 'models/' + subobjectURL;
  400. locationState = locationState + 1;
  401. break;
  402. case FILE_LOCATION_TRY_RELATIVE:
  403. subobjectURL = fileName.substring( 0, fileName.lastIndexOf( '/' ) + 1 ) + subobjectURL;
  404. locationState = locationState + 1;
  405. break;
  406. case FILE_LOCATION_TRY_ABSOLUTE:
  407. if ( triedLowerCase ) {
  408. // Try absolute path
  409. locationState = FILE_LOCATION_NOT_FOUND;
  410. } else {
  411. // Next attempt is lower case
  412. fileName = fileName.toLowerCase();
  413. subobjectURL = fileName;
  414. triedLowerCase = true;
  415. locationState = FILE_LOCATION_TRY_PARTS;
  416. }
  417. break;
  418. }
  419. const loader = this.loader;
  420. const fileLoader = new FileLoader( loader.manager );
  421. fileLoader.setPath( loader.partsLibraryPath );
  422. fileLoader.setRequestHeader( loader.requestHeader );
  423. fileLoader.setWithCredentials( loader.withCredentials );
  424. try {
  425. const text = await fileLoader.loadAsync( subobjectURL );
  426. return text;
  427. } catch ( _ ) {
  428. continue;
  429. }
  430. }
  431. throw new Error( 'LDrawLoader: Subobject "' + fileName + '" could not be loaded.' );
  432. }
  433. parse( text, fileName = null ) {
  434. const loader = this.loader;
  435. // final results
  436. const faces = [];
  437. const lineSegments = [];
  438. const conditionalSegments = [];
  439. const subobjects = [];
  440. const materials = {};
  441. const getLocalMaterial = colorCode => {
  442. return materials[ colorCode ] || null;
  443. };
  444. let type = 'Model';
  445. let category = null;
  446. let keywords = null;
  447. let author = null;
  448. let totalFaces = 0;
  449. // split into lines
  450. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  451. // This is faster than String.split with regex that splits on both
  452. text = text.replace( /\r\n/g, '\n' );
  453. }
  454. const lines = text.split( '\n' );
  455. const numLines = lines.length;
  456. let parsingEmbeddedFiles = false;
  457. let currentEmbeddedFileName = null;
  458. let currentEmbeddedText = null;
  459. let bfcCertified = false;
  460. let bfcCCW = true;
  461. let bfcInverted = false;
  462. let bfcCull = true;
  463. let startingBuildingStep = false;
  464. // Parse all line commands
  465. for ( let lineIndex = 0; lineIndex < numLines; lineIndex ++ ) {
  466. const line = lines[ lineIndex ];
  467. if ( line.length === 0 ) continue;
  468. if ( parsingEmbeddedFiles ) {
  469. if ( line.startsWith( '0 FILE ' ) ) {
  470. // Save previous embedded file in the cache
  471. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  472. // New embedded text file
  473. currentEmbeddedFileName = line.substring( 7 );
  474. currentEmbeddedText = '';
  475. } else {
  476. currentEmbeddedText += line + '\n';
  477. }
  478. continue;
  479. }
  480. const lp = new LineParser( line, lineIndex + 1 );
  481. lp.seekNonSpace();
  482. if ( lp.isAtTheEnd() ) {
  483. // Empty line
  484. continue;
  485. }
  486. // Parse the line type
  487. const lineType = lp.getToken();
  488. let material;
  489. let colorCode;
  490. let segment;
  491. let ccw;
  492. let doubleSided;
  493. let v0, v1, v2, v3, c0, c1;
  494. switch ( lineType ) {
  495. // Line type 0: Comment or META
  496. case '0':
  497. // Parse meta directive
  498. const meta = lp.getToken();
  499. if ( meta ) {
  500. switch ( meta ) {
  501. case '!LDRAW_ORG':
  502. type = lp.getToken();
  503. break;
  504. case '!COLOUR':
  505. material = loader.parseColorMetaDirective( lp );
  506. if ( material ) {
  507. materials[ material.userData.code ] = material;
  508. } else {
  509. console.warn( 'LDrawLoader: Error parsing material' + lp.getLineNumberString() );
  510. }
  511. break;
  512. case '!CATEGORY':
  513. category = lp.getToken();
  514. break;
  515. case '!KEYWORDS':
  516. const newKeywords = lp.getRemainingString().split( ',' );
  517. if ( newKeywords.length > 0 ) {
  518. if ( ! keywords ) {
  519. keywords = [];
  520. }
  521. newKeywords.forEach( function ( keyword ) {
  522. keywords.push( keyword.trim() );
  523. } );
  524. }
  525. break;
  526. case 'FILE':
  527. if ( lineIndex > 0 ) {
  528. // Start embedded text files parsing
  529. parsingEmbeddedFiles = true;
  530. currentEmbeddedFileName = lp.getRemainingString();
  531. currentEmbeddedText = '';
  532. bfcCertified = false;
  533. bfcCCW = true;
  534. }
  535. break;
  536. case 'BFC':
  537. // Changes to the backface culling state
  538. while ( ! lp.isAtTheEnd() ) {
  539. const token = lp.getToken();
  540. switch ( token ) {
  541. case 'CERTIFY':
  542. case 'NOCERTIFY':
  543. bfcCertified = token === 'CERTIFY';
  544. bfcCCW = true;
  545. break;
  546. case 'CW':
  547. case 'CCW':
  548. bfcCCW = token === 'CCW';
  549. break;
  550. case 'INVERTNEXT':
  551. bfcInverted = true;
  552. break;
  553. case 'CLIP':
  554. case 'NOCLIP':
  555. bfcCull = token === 'CLIP';
  556. break;
  557. default:
  558. console.warn( 'THREE.LDrawLoader: BFC directive "' + token + '" is unknown.' );
  559. break;
  560. }
  561. }
  562. break;
  563. case 'STEP':
  564. startingBuildingStep = true;
  565. break;
  566. case 'Author:':
  567. author = lp.getToken();
  568. break;
  569. default:
  570. // Other meta directives are not implemented
  571. break;
  572. }
  573. }
  574. break;
  575. // Line type 1: Sub-object file
  576. case '1':
  577. colorCode = lp.getToken();
  578. material = getLocalMaterial( colorCode );
  579. const posX = parseFloat( lp.getToken() );
  580. const posY = parseFloat( lp.getToken() );
  581. const posZ = parseFloat( lp.getToken() );
  582. const m0 = parseFloat( lp.getToken() );
  583. const m1 = parseFloat( lp.getToken() );
  584. const m2 = parseFloat( lp.getToken() );
  585. const m3 = parseFloat( lp.getToken() );
  586. const m4 = parseFloat( lp.getToken() );
  587. const m5 = parseFloat( lp.getToken() );
  588. const m6 = parseFloat( lp.getToken() );
  589. const m7 = parseFloat( lp.getToken() );
  590. const m8 = parseFloat( lp.getToken() );
  591. const matrix = new Matrix4().set(
  592. m0, m1, m2, posX,
  593. m3, m4, m5, posY,
  594. m6, m7, m8, posZ,
  595. 0, 0, 0, 1
  596. );
  597. let fileName = lp.getRemainingString().trim().replace( /\\/g, '/' );
  598. if ( loader.fileMap[ fileName ] ) {
  599. // Found the subobject path in the preloaded file path map
  600. fileName = loader.fileMap[ fileName ];
  601. } else {
  602. // Standardized subfolders
  603. if ( fileName.startsWith( 's/' ) ) {
  604. fileName = 'parts/' + fileName;
  605. } else if ( fileName.startsWith( '48/' ) ) {
  606. fileName = 'p/' + fileName;
  607. }
  608. }
  609. subobjects.push( {
  610. material: material,
  611. colorCode: colorCode,
  612. matrix: matrix,
  613. fileName: fileName,
  614. inverted: bfcInverted,
  615. startingBuildingStep: startingBuildingStep
  616. } );
  617. startingBuildingStep = false;
  618. bfcInverted = false;
  619. break;
  620. // Line type 2: Line segment
  621. case '2':
  622. colorCode = lp.getToken();
  623. material = getLocalMaterial( colorCode );
  624. v0 = lp.getVector();
  625. v1 = lp.getVector();
  626. segment = {
  627. material: material,
  628. colorCode: colorCode,
  629. vertices: [ v0, v1 ],
  630. };
  631. lineSegments.push( segment );
  632. break;
  633. // Line type 5: Conditional Line segment
  634. case '5':
  635. colorCode = lp.getToken();
  636. material = getLocalMaterial( colorCode );
  637. v0 = lp.getVector();
  638. v1 = lp.getVector();
  639. c0 = lp.getVector();
  640. c1 = lp.getVector();
  641. segment = {
  642. material: material,
  643. colorCode: colorCode,
  644. vertices: [ v0, v1 ],
  645. controlPoints: [ c0, c1 ],
  646. };
  647. conditionalSegments.push( segment );
  648. break;
  649. // Line type 3: Triangle
  650. case '3':
  651. colorCode = lp.getToken();
  652. material = getLocalMaterial( colorCode );
  653. ccw = bfcCCW;
  654. doubleSided = ! bfcCertified || ! bfcCull;
  655. if ( ccw === true ) {
  656. v0 = lp.getVector();
  657. v1 = lp.getVector();
  658. v2 = lp.getVector();
  659. } else {
  660. v2 = lp.getVector();
  661. v1 = lp.getVector();
  662. v0 = lp.getVector();
  663. }
  664. faces.push( {
  665. material: material,
  666. colorCode: colorCode,
  667. faceNormal: null,
  668. vertices: [ v0, v1, v2 ],
  669. normals: [ null, null, null ],
  670. } );
  671. totalFaces ++;
  672. if ( doubleSided === true ) {
  673. faces.push( {
  674. material: material,
  675. colorCode: colorCode,
  676. faceNormal: null,
  677. vertices: [ v2, v1, v0 ],
  678. normals: [ null, null, null ],
  679. } );
  680. totalFaces ++;
  681. }
  682. break;
  683. // Line type 4: Quadrilateral
  684. case '4':
  685. colorCode = lp.getToken();
  686. material = getLocalMaterial( colorCode );
  687. ccw = bfcCCW;
  688. doubleSided = ! bfcCertified || ! bfcCull;
  689. if ( ccw === true ) {
  690. v0 = lp.getVector();
  691. v1 = lp.getVector();
  692. v2 = lp.getVector();
  693. v3 = lp.getVector();
  694. } else {
  695. v3 = lp.getVector();
  696. v2 = lp.getVector();
  697. v1 = lp.getVector();
  698. v0 = lp.getVector();
  699. }
  700. // specifically place the triangle diagonal in the v0 and v1 slots so we can
  701. // account for the doubling of vertices later when smoothing normals.
  702. faces.push( {
  703. material: material,
  704. colorCode: colorCode,
  705. faceNormal: null,
  706. vertices: [ v0, v1, v2, v3 ],
  707. normals: [ null, null, null, null ],
  708. } );
  709. totalFaces += 2;
  710. if ( doubleSided === true ) {
  711. faces.push( {
  712. material: material,
  713. colorCode: colorCode,
  714. faceNormal: null,
  715. vertices: [ v3, v2, v1, v0 ],
  716. normals: [ null, null, null, null ],
  717. } );
  718. totalFaces += 2;
  719. }
  720. break;
  721. default:
  722. throw new Error( 'LDrawLoader: Unknown line type "' + lineType + '"' + lp.getLineNumberString() + '.' );
  723. }
  724. }
  725. if ( parsingEmbeddedFiles ) {
  726. this.setData( currentEmbeddedFileName, currentEmbeddedText );
  727. }
  728. return {
  729. faces,
  730. conditionalSegments,
  731. lineSegments,
  732. type,
  733. category,
  734. keywords,
  735. author,
  736. subobjects,
  737. totalFaces,
  738. startingBuildingStep,
  739. materials,
  740. fileName,
  741. group: null
  742. };
  743. }
  744. // returns an (optionally cloned) instance of the data
  745. getData( fileName, clone = true ) {
  746. const key = fileName.toLowerCase();
  747. const result = this._cache[ key ];
  748. if ( result === null || result instanceof Promise ) {
  749. return null;
  750. }
  751. if ( clone ) {
  752. return this.cloneResult( result );
  753. } else {
  754. return result;
  755. }
  756. }
  757. // kicks off a fetch and parse of the requested data if it hasn't already been loaded. Returns when
  758. // the data is ready to use and can be retrieved synchronously with "getData".
  759. async ensureDataLoaded( fileName ) {
  760. const key = fileName.toLowerCase();
  761. if ( ! ( key in this._cache ) ) {
  762. // replace the promise with a copy of the parsed data for immediate processing
  763. this._cache[ key ] = this.fetchData( fileName ).then( text => {
  764. const info = this.parse( text, fileName );
  765. this._cache[ key ] = info;
  766. return info;
  767. } );
  768. }
  769. await this._cache[ key ];
  770. }
  771. // sets the data in the cache from parsed data
  772. setData( fileName, text ) {
  773. const key = fileName.toLowerCase();
  774. this._cache[ key ] = this.parse( text, fileName );
  775. }
  776. }
  777. // returns the material for an associated color code. If the color code is 16 for a face or 24 for
  778. // an edge then the passthroughColorCode is used.
  779. function getMaterialFromCode( colorCode, parentColorCode, materialHierarchy, forEdge ) {
  780. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  781. if ( isPassthrough ) {
  782. colorCode = parentColorCode;
  783. }
  784. return materialHierarchy[ colorCode ] || null;
  785. }
  786. // Class used to parse and build LDraw parts as three.js objects and cache them if they're a "Part" type.
  787. class LDrawPartsGeometryCache {
  788. constructor( loader ) {
  789. this.loader = loader;
  790. this.parseCache = new LDrawParsedCache( loader );
  791. this._cache = {};
  792. }
  793. // Convert the given file information into a mesh by processing subobjects.
  794. async processIntoMesh( info ) {
  795. const loader = this.loader;
  796. const parseCache = this.parseCache;
  797. const faceMaterials = new Set();
  798. // Processes the part subobject information to load child parts and merge geometry onto part
  799. // piece object.
  800. const processInfoSubobjects = async ( info, subobject = null ) => {
  801. const subobjects = info.subobjects;
  802. const promises = [];
  803. // Trigger load of all subobjects. If a subobject isn't a primitive then load it as a separate
  804. // group which lets instruction steps apply correctly.
  805. for ( let i = 0, l = subobjects.length; i < l; i ++ ) {
  806. const subobject = subobjects[ i ];
  807. const promise = parseCache.ensureDataLoaded( subobject.fileName ).then( () => {
  808. const subobjectInfo = parseCache.getData( subobject.fileName, false );
  809. if ( ! isPrimitiveType( subobjectInfo.type ) ) {
  810. return this.loadModel( subobject.fileName ).catch( error => {
  811. console.warn( error );
  812. return null;
  813. } );
  814. }
  815. return processInfoSubobjects( parseCache.getData( subobject.fileName ), subobject );
  816. } );
  817. promises.push( promise );
  818. }
  819. const group = new Group();
  820. group.userData.category = info.category;
  821. group.userData.keywords = info.keywords;
  822. group.userData.author = info.author;
  823. group.userData.type = info.type;
  824. group.userData.fileName = info.fileName;
  825. info.group = group;
  826. const subobjectInfos = await Promise.all( promises );
  827. for ( let i = 0, l = subobjectInfos.length; i < l; i ++ ) {
  828. const subobject = info.subobjects[ i ];
  829. const subobjectInfo = subobjectInfos[ i ];
  830. if ( subobjectInfo === null ) {
  831. // the subobject failed to load
  832. continue;
  833. }
  834. // if the subobject was loaded as a separate group then apply the parent scopes materials
  835. if ( subobjectInfo.isGroup ) {
  836. const subobjectGroup = subobjectInfo;
  837. subobject.matrix.decompose( subobjectGroup.position, subobjectGroup.quaternion, subobjectGroup.scale );
  838. subobjectGroup.userData.startingBuildingStep = subobject.startingBuildingStep;
  839. subobjectGroup.name = subobject.fileName;
  840. loader.applyMaterialsToMesh( subobjectGroup, subobject.colorCode, info.materials );
  841. subobjectGroup.userData.colorCode = subobject.colorCode;
  842. group.add( subobjectGroup );
  843. continue;
  844. }
  845. // add the subobject group if it has children in case it has both children and primitives
  846. if ( subobjectInfo.group.children.length ) {
  847. group.add( subobjectInfo.group );
  848. }
  849. // transform the primitives into the local space of the parent piece and append them to
  850. // to the parent primitives list.
  851. const parentLineSegments = info.lineSegments;
  852. const parentConditionalSegments = info.conditionalSegments;
  853. const parentFaces = info.faces;
  854. const lineSegments = subobjectInfo.lineSegments;
  855. const conditionalSegments = subobjectInfo.conditionalSegments;
  856. const faces = subobjectInfo.faces;
  857. const matrix = subobject.matrix;
  858. const inverted = subobject.inverted;
  859. const matrixScaleInverted = matrix.determinant() < 0;
  860. const colorCode = subobject.colorCode;
  861. const lineColorCode = colorCode === MAIN_COLOUR_CODE ? MAIN_EDGE_COLOUR_CODE : colorCode;
  862. for ( let i = 0, l = lineSegments.length; i < l; i ++ ) {
  863. const ls = lineSegments[ i ];
  864. const vertices = ls.vertices;
  865. vertices[ 0 ].applyMatrix4( matrix );
  866. vertices[ 1 ].applyMatrix4( matrix );
  867. ls.colorCode = ls.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : ls.colorCode;
  868. ls.material = ls.material || getMaterialFromCode( ls.colorCode, ls.colorCode, info.materials, true );
  869. parentLineSegments.push( ls );
  870. }
  871. for ( let i = 0, l = conditionalSegments.length; i < l; i ++ ) {
  872. const os = conditionalSegments[ i ];
  873. const vertices = os.vertices;
  874. const controlPoints = os.controlPoints;
  875. vertices[ 0 ].applyMatrix4( matrix );
  876. vertices[ 1 ].applyMatrix4( matrix );
  877. controlPoints[ 0 ].applyMatrix4( matrix );
  878. controlPoints[ 1 ].applyMatrix4( matrix );
  879. os.colorCode = os.colorCode === MAIN_EDGE_COLOUR_CODE ? lineColorCode : os.colorCode;
  880. os.material = os.material || getMaterialFromCode( os.colorCode, os.colorCode, info.materials, true );
  881. parentConditionalSegments.push( os );
  882. }
  883. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  884. const tri = faces[ i ];
  885. const vertices = tri.vertices;
  886. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  887. vertices[ i ].applyMatrix4( matrix );
  888. }
  889. tri.colorCode = tri.colorCode === MAIN_COLOUR_CODE ? colorCode : tri.colorCode;
  890. tri.material = tri.material || getMaterialFromCode( tri.colorCode, colorCode, info.materials, false );
  891. faceMaterials.add( tri.colorCode );
  892. // If the scale of the object is negated then the triangle winding order
  893. // needs to be flipped.
  894. if ( matrixScaleInverted !== inverted ) {
  895. vertices.reverse();
  896. }
  897. parentFaces.push( tri );
  898. }
  899. info.totalFaces += subobjectInfo.totalFaces;
  900. }
  901. // Apply the parent subobjects pass through material code to this object. This is done several times due
  902. // to material scoping.
  903. if ( subobject ) {
  904. loader.applyMaterialsToMesh( group, subobject.colorCode, info.materials );
  905. group.userData.colorCode = subobject.colorCode;
  906. }
  907. return info;
  908. };
  909. // Track material use to see if we need to use the normal smooth slow path for hard edges.
  910. for ( let i = 0, l = info.faces; i < l; i ++ ) {
  911. faceMaterials.add( info.faces[ i ].colorCode );
  912. }
  913. await processInfoSubobjects( info );
  914. if ( loader.smoothNormals ) {
  915. const checkSubSegments = faceMaterials.size > 1;
  916. generateFaceNormals( info.faces );
  917. smoothNormals( info.faces, info.lineSegments, checkSubSegments );
  918. }
  919. // Add the primitive objects and metadata.
  920. const group = info.group;
  921. if ( info.faces.length > 0 ) {
  922. group.add( createObject( this.loader, info.faces, 3, false, info.totalFaces ) );
  923. }
  924. if ( info.lineSegments.length > 0 ) {
  925. group.add( createObject( this.loader, info.lineSegments, 2 ) );
  926. }
  927. if ( info.conditionalSegments.length > 0 ) {
  928. group.add( createObject( this.loader, info.conditionalSegments, 2, true ) );
  929. }
  930. return group;
  931. }
  932. hasCachedModel( fileName ) {
  933. return fileName !== null && fileName.toLowerCase() in this._cache;
  934. }
  935. async getCachedModel( fileName ) {
  936. if ( fileName !== null && this.hasCachedModel( fileName ) ) {
  937. const key = fileName.toLowerCase();
  938. const group = await this._cache[ key ];
  939. return group.clone();
  940. } else {
  941. return null;
  942. }
  943. }
  944. // Loads and parses the model with the given file name. Returns a cached copy if available.
  945. async loadModel( fileName ) {
  946. const parseCache = this.parseCache;
  947. const key = fileName.toLowerCase();
  948. if ( this.hasCachedModel( fileName ) ) {
  949. // Return cached model if available.
  950. return this.getCachedModel( fileName );
  951. } else {
  952. // Otherwise parse a new model.
  953. // Ensure the file data is loaded and pre parsed.
  954. await parseCache.ensureDataLoaded( fileName );
  955. const info = parseCache.getData( fileName );
  956. const promise = this.processIntoMesh( info );
  957. // Now that the file has loaded it's possible that another part parse has been waiting in parallel
  958. // so check the cache again to see if it's been added since the last async operation so we don't
  959. // do unnecessary work.
  960. if ( this.hasCachedModel( fileName ) ) {
  961. return this.getCachedModel( fileName );
  962. }
  963. // Cache object if it's a part so it can be reused later.
  964. if ( isPartType( info.type ) ) {
  965. this._cache[ key ] = promise;
  966. }
  967. // return a copy
  968. const group = await promise;
  969. return group.clone();
  970. }
  971. }
  972. // parses the given model text into a renderable object. Returns cached copy if available.
  973. async parseModel( text ) {
  974. const parseCache = this.parseCache;
  975. const info = parseCache.parse( text );
  976. if ( isPartType( info.type ) && this.hasCachedModel( info.fileName ) ) {
  977. return this.getCachedModel( info.fileName );
  978. }
  979. return this.processIntoMesh( info );
  980. }
  981. }
  982. function sortByMaterial( a, b ) {
  983. if ( a.colorCode === b.colorCode ) {
  984. return 0;
  985. }
  986. if ( a.colorCode < b.colorCode ) {
  987. return - 1;
  988. }
  989. return 1;
  990. }
  991. function createObject( loader, elements, elementSize, isConditionalSegments = false, totalElements = null ) {
  992. // Creates a LineSegments (elementSize = 2) or a Mesh (elementSize = 3 )
  993. // With per face / segment material, implemented with mesh groups and materials array
  994. // Sort the faces or line segments by color code to make later the mesh groups
  995. elements.sort( sortByMaterial );
  996. if ( totalElements === null ) {
  997. totalElements = elements.length;
  998. }
  999. const positions = new Float32Array( elementSize * totalElements * 3 );
  1000. const normals = elementSize === 3 ? new Float32Array( elementSize * totalElements * 3 ) : null;
  1001. const materials = [];
  1002. const quadArray = new Array( 6 );
  1003. const bufferGeometry = new BufferGeometry();
  1004. let prevMaterial = null;
  1005. let index0 = 0;
  1006. let numGroupVerts = 0;
  1007. let offset = 0;
  1008. for ( let iElem = 0, nElem = elements.length; iElem < nElem; iElem ++ ) {
  1009. const elem = elements[ iElem ];
  1010. let vertices = elem.vertices;
  1011. if ( vertices.length === 4 ) {
  1012. quadArray[ 0 ] = vertices[ 0 ];
  1013. quadArray[ 1 ] = vertices[ 1 ];
  1014. quadArray[ 2 ] = vertices[ 2 ];
  1015. quadArray[ 3 ] = vertices[ 0 ];
  1016. quadArray[ 4 ] = vertices[ 2 ];
  1017. quadArray[ 5 ] = vertices[ 3 ];
  1018. vertices = quadArray;
  1019. }
  1020. for ( let j = 0, l = vertices.length; j < l; j ++ ) {
  1021. const v = vertices[ j ];
  1022. const index = offset + j * 3;
  1023. positions[ index + 0 ] = v.x;
  1024. positions[ index + 1 ] = v.y;
  1025. positions[ index + 2 ] = v.z;
  1026. }
  1027. // create the normals array if this is a set of faces
  1028. if ( elementSize === 3 ) {
  1029. if ( ! elem.faceNormal ) {
  1030. const v0 = vertices[ 0 ];
  1031. const v1 = vertices[ 1 ];
  1032. const v2 = vertices[ 2 ];
  1033. _tempVec0.subVectors( v1, v0 );
  1034. _tempVec1.subVectors( v2, v1 );
  1035. elem.faceNormal = new Vector3()
  1036. .crossVectors( _tempVec0, _tempVec1 )
  1037. .normalize();
  1038. }
  1039. let elemNormals = elem.normals;
  1040. if ( elemNormals.length === 4 ) {
  1041. quadArray[ 0 ] = elemNormals[ 0 ];
  1042. quadArray[ 1 ] = elemNormals[ 1 ];
  1043. quadArray[ 2 ] = elemNormals[ 2 ];
  1044. quadArray[ 3 ] = elemNormals[ 0 ];
  1045. quadArray[ 4 ] = elemNormals[ 2 ];
  1046. quadArray[ 5 ] = elemNormals[ 3 ];
  1047. elemNormals = quadArray;
  1048. }
  1049. for ( let j = 0, l = elemNormals.length; j < l; j ++ ) {
  1050. // use face normal if a vertex normal is not provided
  1051. let n = elem.faceNormal;
  1052. if ( elemNormals[ j ] ) {
  1053. n = elemNormals[ j ].norm;
  1054. }
  1055. const index = offset + j * 3;
  1056. normals[ index + 0 ] = n.x;
  1057. normals[ index + 1 ] = n.y;
  1058. normals[ index + 2 ] = n.z;
  1059. }
  1060. }
  1061. if ( prevMaterial !== elem.colorCode ) {
  1062. if ( prevMaterial !== null ) {
  1063. bufferGeometry.addGroup( index0, numGroupVerts, materials.length - 1 );
  1064. }
  1065. const material = elem.material;
  1066. if ( material !== null ) {
  1067. if ( elementSize === 3 ) {
  1068. materials.push( material );
  1069. } else if ( elementSize === 2 ) {
  1070. if ( isConditionalSegments ) {
  1071. const edgeMaterial = loader.edgeMaterialCache.get( material );
  1072. materials.push( loader.conditionalEdgeMaterialCache.get( edgeMaterial ) );
  1073. } else {
  1074. materials.push( loader.edgeMaterialCache.get( material ) );
  1075. }
  1076. }
  1077. } else {
  1078. // If a material has not been made available yet then keep the color code string in the material array
  1079. // to save the spot for the material once a parent scopes materials are being applied to the object.
  1080. materials.push( elem.colorCode );
  1081. }
  1082. prevMaterial = elem.colorCode;
  1083. index0 = offset / 3;
  1084. numGroupVerts = vertices.length;
  1085. } else {
  1086. numGroupVerts += vertices.length;
  1087. }
  1088. offset += 3 * vertices.length;
  1089. }
  1090. if ( numGroupVerts > 0 ) {
  1091. bufferGeometry.addGroup( index0, Infinity, materials.length - 1 );
  1092. }
  1093. bufferGeometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1094. if ( normals !== null ) {
  1095. bufferGeometry.setAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  1096. }
  1097. let object3d = null;
  1098. if ( elementSize === 2 ) {
  1099. if ( isConditionalSegments ) {
  1100. object3d = new ConditionalLineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1101. } else {
  1102. object3d = new LineSegments( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1103. }
  1104. } else if ( elementSize === 3 ) {
  1105. object3d = new Mesh( bufferGeometry, materials.length === 1 ? materials[ 0 ] : materials );
  1106. }
  1107. if ( isConditionalSegments ) {
  1108. object3d.isConditionalLine = true;
  1109. const controlArray0 = new Float32Array( elements.length * 3 * 2 );
  1110. const controlArray1 = new Float32Array( elements.length * 3 * 2 );
  1111. const directionArray = new Float32Array( elements.length * 3 * 2 );
  1112. for ( let i = 0, l = elements.length; i < l; i ++ ) {
  1113. const os = elements[ i ];
  1114. const vertices = os.vertices;
  1115. const controlPoints = os.controlPoints;
  1116. const c0 = controlPoints[ 0 ];
  1117. const c1 = controlPoints[ 1 ];
  1118. const v0 = vertices[ 0 ];
  1119. const v1 = vertices[ 1 ];
  1120. const index = i * 3 * 2;
  1121. controlArray0[ index + 0 ] = c0.x;
  1122. controlArray0[ index + 1 ] = c0.y;
  1123. controlArray0[ index + 2 ] = c0.z;
  1124. controlArray0[ index + 3 ] = c0.x;
  1125. controlArray0[ index + 4 ] = c0.y;
  1126. controlArray0[ index + 5 ] = c0.z;
  1127. controlArray1[ index + 0 ] = c1.x;
  1128. controlArray1[ index + 1 ] = c1.y;
  1129. controlArray1[ index + 2 ] = c1.z;
  1130. controlArray1[ index + 3 ] = c1.x;
  1131. controlArray1[ index + 4 ] = c1.y;
  1132. controlArray1[ index + 5 ] = c1.z;
  1133. directionArray[ index + 0 ] = v1.x - v0.x;
  1134. directionArray[ index + 1 ] = v1.y - v0.y;
  1135. directionArray[ index + 2 ] = v1.z - v0.z;
  1136. directionArray[ index + 3 ] = v1.x - v0.x;
  1137. directionArray[ index + 4 ] = v1.y - v0.y;
  1138. directionArray[ index + 5 ] = v1.z - v0.z;
  1139. }
  1140. bufferGeometry.setAttribute( 'control0', new BufferAttribute( controlArray0, 3, false ) );
  1141. bufferGeometry.setAttribute( 'control1', new BufferAttribute( controlArray1, 3, false ) );
  1142. bufferGeometry.setAttribute( 'direction', new BufferAttribute( directionArray, 3, false ) );
  1143. }
  1144. return object3d;
  1145. }
  1146. /**
  1147. * A loader for the LDraw format.
  1148. *
  1149. * [LDraw]{@link https://ldraw.org/} (LEGO Draw) is an [open format specification]{@link https://ldraw.org/article/218.html}
  1150. * for describing LEGO and other construction set 3D models.
  1151. *
  1152. * An LDraw asset (a text file usually with extension .ldr, .dat or .txt) can describe just a single construction
  1153. * piece, or an entire model. In the case of a model the LDraw file can reference other LDraw files, which are
  1154. * loaded from a library path set with `setPartsLibraryPath`. You usually download the LDraw official parts library,
  1155. * extract to a folder and point setPartsLibraryPath to it.
  1156. *
  1157. * Library parts will be loaded by trial and error in subfolders 'parts', 'p' and 'models'. These file accesses
  1158. * are not optimal for web environment, so a script tool has been made to pack an LDraw file with all its dependencies
  1159. * into a single file, which loads much faster. See section 'Packing LDraw models'. The LDrawLoader example loads
  1160. * several packed files. The official parts library is not included due to its large size.
  1161. *
  1162. * `LDrawLoader` supports the following extensions:
  1163. * - !COLOUR: Color and surface finish declarations.
  1164. * - BFC: Back Face Culling specification.
  1165. * - !CATEGORY: Model/part category declarations.
  1166. * - !KEYWORDS: Model/part keywords declarations.
  1167. *
  1168. * ```js
  1169. * const loader = new LDrawLoader();
  1170. * loader.setConditionalLineMaterial( LDrawConditionalLineMaterial ); // the type of line material depends on the used renderer
  1171. * const object = await loader.loadAsync( 'models/ldraw/officialLibrary/models/car.ldr_Packed.mpd' );
  1172. * scene.add( object );
  1173. * ```
  1174. *
  1175. * @augments Loader
  1176. */
  1177. class LDrawLoader extends Loader {
  1178. /**
  1179. * Constructs a new LDraw loader.
  1180. *
  1181. * @param {LoadingManager} [manager] - The loading manager.
  1182. */
  1183. constructor( manager ) {
  1184. super( manager );
  1185. // Array of THREE.Material
  1186. this.materials = [];
  1187. this.materialLibrary = {};
  1188. this.edgeMaterialCache = new WeakMap();
  1189. this.conditionalEdgeMaterialCache = new WeakMap();
  1190. // This also allows to handle the embedded text files ("0 FILE" lines)
  1191. this.partsCache = new LDrawPartsGeometryCache( this );
  1192. // 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.
  1193. this.fileMap = {};
  1194. // If this flag is set to true the vertex normals will be smoothed.
  1195. this.smoothNormals = true;
  1196. // The path to load parts from the LDraw parts library from.
  1197. this.partsLibraryPath = '';
  1198. // this material type must be injected via setConditionalLineMaterial()
  1199. this.ConditionalLineMaterial = null;
  1200. // Material assigned to not available colors for meshes and edges
  1201. this.missingColorMaterial = new MeshStandardMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF, roughness: 0.3, metalness: 0 } );
  1202. this.missingEdgeColorMaterial = new LineBasicMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, color: 0xFF00FF } );
  1203. this.missingConditionalEdgeColorMaterial = null;
  1204. this.edgeMaterialCache.set( this.missingColorMaterial, this.missingEdgeColorMaterial );
  1205. this.conditionalEdgeMaterialCache.set( this.missingEdgeColorMaterial, this.missingConditionalEdgeColorMaterial );
  1206. }
  1207. /**
  1208. * This method must be called prior to `load()` unless the model to load does not reference
  1209. * library parts (usually it will be a model with all its parts packed in a single file).
  1210. *
  1211. * @param {string} path - Path to library parts files to load referenced parts from.
  1212. * This is different from Loader.setPath, which indicates the path to load the main asset from.
  1213. * @return {LDrawLoader} A reference to this loader.
  1214. */
  1215. setPartsLibraryPath( path ) {
  1216. this.partsLibraryPath = path;
  1217. return this;
  1218. }
  1219. /**
  1220. * Sets the conditional line material type which depends on the used renderer.
  1221. * Use {@link LDrawConditionalLineMaterial} when using `WebGLRenderer` and
  1222. * {@link LDrawConditionalLineNodeMaterial} when using `WebGPURenderer`.
  1223. *
  1224. * @param {(LDrawConditionalLineMaterial.constructor|LDrawConditionalLineNodeMaterial.constructor)} type - The conditional line material type.
  1225. * @return {LDrawLoader} A reference to this loader.
  1226. */
  1227. setConditionalLineMaterial( type ) {
  1228. this.ConditionalLineMaterial = type;
  1229. this.missingConditionalEdgeColorMaterial = new this.ConditionalLineMaterial( { name: Loader.DEFAULT_MATERIAL_NAME, fog: true, color: 0xFF00FF } );
  1230. return this;
  1231. }
  1232. /**
  1233. * This async method preloads materials from a single LDraw file. In the official
  1234. * parts library there is a special file which is loaded always the first (LDConfig.ldr)
  1235. * and contains all the standard color codes. This method is intended to be used with
  1236. * not packed files, for example in an editor where materials are preloaded and parts
  1237. * are loaded on demand.
  1238. *
  1239. * @async
  1240. * @param {string} url - Path of the LDraw materials asset.
  1241. * @return {Promise} A Promise that resolves when the preload has finished.
  1242. */
  1243. async preloadMaterials( url ) {
  1244. const fileLoader = new FileLoader( this.manager );
  1245. fileLoader.setPath( this.path );
  1246. fileLoader.setRequestHeader( this.requestHeader );
  1247. fileLoader.setWithCredentials( this.withCredentials );
  1248. const text = await fileLoader.loadAsync( url );
  1249. const colorLineRegex = /^0 !COLOUR/;
  1250. const lines = text.split( /[\n\r]/g );
  1251. const materials = [];
  1252. for ( let i = 0, l = lines.length; i < l; i ++ ) {
  1253. const line = lines[ i ];
  1254. if ( colorLineRegex.test( line ) ) {
  1255. const directive = line.replace( colorLineRegex, '' );
  1256. const material = this.parseColorMetaDirective( new LineParser( directive ) );
  1257. materials.push( material );
  1258. }
  1259. }
  1260. this.setMaterials( materials );
  1261. }
  1262. /**
  1263. * Starts loading from the given URL and passes the loaded LDraw asset
  1264. * to the `onLoad()` callback.
  1265. *
  1266. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  1267. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  1268. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  1269. * @param {onErrorCallback} onError - Executed when errors occur.
  1270. */
  1271. load( url, onLoad, onProgress, onError ) {
  1272. const fileLoader = new FileLoader( this.manager );
  1273. fileLoader.setPath( this.path );
  1274. fileLoader.setRequestHeader( this.requestHeader );
  1275. fileLoader.setWithCredentials( this.withCredentials );
  1276. fileLoader.load( url, text => {
  1277. // Initializes the materials library with default materials
  1278. this.setMaterials( [] );
  1279. this.partsCache
  1280. .parseModel( text )
  1281. .then( group => {
  1282. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1283. this.computeBuildingSteps( group );
  1284. group.userData.fileName = url;
  1285. onLoad( group );
  1286. } )
  1287. .catch( onError );
  1288. }, onProgress, onError );
  1289. }
  1290. /**
  1291. * Parses the given LDraw data and returns the resulting group.
  1292. *
  1293. * @param {string} text - The raw VRML data as a string.
  1294. * @param {function(Group)} onLoad - Executed when the loading/parsing process has been finished.
  1295. * @param {onErrorCallback} onError - Executed when errors occur.
  1296. */
  1297. parse( text, onLoad, onError ) {
  1298. this.partsCache
  1299. .parseModel( text )
  1300. .then( group => {
  1301. this.applyMaterialsToMesh( group, MAIN_COLOUR_CODE, this.materialLibrary, true );
  1302. this.computeBuildingSteps( group );
  1303. group.userData.fileName = '';
  1304. onLoad( group );
  1305. } )
  1306. .catch( onError );
  1307. }
  1308. setMaterials( materials ) {
  1309. this.materialLibrary = {};
  1310. this.materials = [];
  1311. for ( let i = 0, l = materials.length; i < l; i ++ ) {
  1312. this.addMaterial( materials[ i ] );
  1313. }
  1314. // Add default main triangle and line edge materials (used in pieces that can be colored with a main color)
  1315. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Main_Colour CODE 16 VALUE #FF8080 EDGE #333333' ) ) );
  1316. this.addMaterial( this.parseColorMetaDirective( new LineParser( 'Edge_Colour CODE 24 VALUE #A0A0A0 EDGE #333333' ) ) );
  1317. return this;
  1318. }
  1319. /**
  1320. * Sets a map which maps referenced library filenames to new filenames.
  1321. * If a fileMap is not specified (the default), library parts will be accessed by trial and
  1322. * error in subfolders 'parts', 'p' and 'models'.
  1323. *
  1324. * @param {Object<string,string>} fileMap - The file map to set.
  1325. * @return {LDrawLoader} A reference to this loader.
  1326. */
  1327. setFileMap( fileMap ) {
  1328. this.fileMap = fileMap;
  1329. return this;
  1330. }
  1331. addMaterial( material ) {
  1332. // Adds a material to the material library which is on top of the parse scopes stack. And also to the materials array
  1333. const matLib = this.materialLibrary;
  1334. if ( ! matLib[ material.userData.code ] ) {
  1335. this.materials.push( material );
  1336. matLib[ material.userData.code ] = material;
  1337. }
  1338. return this;
  1339. }
  1340. /**
  1341. * Returns a material for the given color code.
  1342. *
  1343. * @param {string} colorCode - The color code.
  1344. * @return {?Material} The material. Returns `null` if no material has been found.
  1345. */
  1346. getMaterial( colorCode ) {
  1347. if ( colorCode.startsWith( '0x2' ) ) {
  1348. // Special 'direct' material value (RGB color)
  1349. const color = colorCode.substring( 3 );
  1350. return this.parseColorMetaDirective( new LineParser( 'Direct_Color_' + color + ' CODE -1 VALUE #' + color + ' EDGE #' + color + '' ) );
  1351. }
  1352. return this.materialLibrary[ colorCode ] || null;
  1353. }
  1354. // Applies the appropriate materials to a prebuilt hierarchy of geometry. Assumes that color codes are present
  1355. // in the material array if they need to be filled in.
  1356. applyMaterialsToMesh( group, parentColorCode, materialHierarchy, finalMaterialPass = false ) {
  1357. // find any missing materials as indicated by a color code string and replace it with a material from the current material lib
  1358. const loader = this;
  1359. const parentIsPassthrough = parentColorCode === MAIN_COLOUR_CODE;
  1360. group.traverse( c => {
  1361. if ( c.isMesh || c.isLineSegments ) {
  1362. if ( Array.isArray( c.material ) ) {
  1363. for ( let i = 0, l = c.material.length; i < l; i ++ ) {
  1364. if ( ! c.material[ i ].isMaterial ) {
  1365. c.material[ i ] = getMaterial( c, c.material[ i ] );
  1366. }
  1367. }
  1368. } else if ( ! c.material.isMaterial ) {
  1369. c.material = getMaterial( c, c.material );
  1370. }
  1371. }
  1372. } );
  1373. // Returns the appropriate material for the object (line or face) given color code. If the code is "pass through"
  1374. // (24 for lines, 16 for edges) then the pass through color code is used. If that is also pass through then it's
  1375. // simply returned for the subsequent material application.
  1376. function getMaterial( c, colorCode ) {
  1377. // if our parent is a passthrough color code and we don't have the current material color available then
  1378. // return early.
  1379. if ( parentIsPassthrough && ! ( colorCode in materialHierarchy ) && ! finalMaterialPass ) {
  1380. return colorCode;
  1381. }
  1382. const forEdge = c.isLineSegments || c.isConditionalLine;
  1383. const isPassthrough = ! forEdge && colorCode === MAIN_COLOUR_CODE || forEdge && colorCode === MAIN_EDGE_COLOUR_CODE;
  1384. if ( isPassthrough ) {
  1385. colorCode = parentColorCode;
  1386. }
  1387. let material = null;
  1388. if ( colorCode in materialHierarchy ) {
  1389. material = materialHierarchy[ colorCode ];
  1390. } else if ( finalMaterialPass ) {
  1391. // see if we can get the final material from from the "getMaterial" function which will attempt to
  1392. // parse the "direct" colors
  1393. material = loader.getMaterial( colorCode );
  1394. if ( material === null ) {
  1395. // otherwise throw a warning if this is final opportunity to set the material
  1396. console.warn( `LDrawLoader: Material properties for code ${ colorCode } not available.` );
  1397. // And return the 'missing color' material
  1398. material = loader.missingColorMaterial;
  1399. }
  1400. } else {
  1401. return colorCode;
  1402. }
  1403. if ( c.isLineSegments ) {
  1404. material = loader.edgeMaterialCache.get( material );
  1405. if ( c.isConditionalLine ) {
  1406. material = loader.conditionalEdgeMaterialCache.get( material );
  1407. }
  1408. }
  1409. return material;
  1410. }
  1411. }
  1412. /**
  1413. * Returns the Material for the main LDraw color.
  1414. *
  1415. * For an already loaded LDraw asset, returns the Material associated with the main color code.
  1416. * This method can be useful to modify the main material of a model or part that exposes it.
  1417. *
  1418. * The main color code is the standard way to color an LDraw part. It is '16' for triangles and
  1419. * '24' for edges. Usually a complete model will not expose the main color (that is, no part
  1420. * uses the code '16' at the top level, because they are assigned other specific colors) An LDraw
  1421. * part file on the other hand will expose the code '16' to be colored, and can have additional
  1422. * fixed colors.
  1423. *
  1424. * @return {?Material} The material. Returns `null` if no material has been found.
  1425. */
  1426. getMainMaterial() {
  1427. return this.getMaterial( MAIN_COLOUR_CODE );
  1428. }
  1429. /**
  1430. * Returns the material for the edges main LDraw color.
  1431. *
  1432. * @return {?Material} The material. Returns `null` if no material has been found.
  1433. */
  1434. getMainEdgeMaterial() {
  1435. const mat = this.getMaterial( MAIN_EDGE_COLOUR_CODE );
  1436. return mat ? this.edgeMaterialCache.get( mat ) : null;
  1437. }
  1438. parseColorMetaDirective( lineParser ) {
  1439. // Parses a color definition and returns a THREE.Material
  1440. let code = null;
  1441. // Triangle and line colors
  1442. let fillColor = '#FF00FF';
  1443. let edgeColor = '#FF00FF';
  1444. // Transparency
  1445. let alpha = 1;
  1446. let isTransparent = false;
  1447. // Self-illumination:
  1448. let luminance = 0;
  1449. let finishType = FINISH_TYPE_DEFAULT;
  1450. let edgeMaterial = null;
  1451. const name = lineParser.getToken();
  1452. if ( ! name ) {
  1453. throw new Error( 'LDrawLoader: Material name was expected after "!COLOUR tag' + lineParser.getLineNumberString() + '.' );
  1454. }
  1455. // Parse tag tokens and their parameters
  1456. let token = null;
  1457. while ( true ) {
  1458. token = lineParser.getToken();
  1459. if ( ! token ) {
  1460. break;
  1461. }
  1462. if ( ! parseLuminance( token ) ) {
  1463. switch ( token.toUpperCase() ) {
  1464. case 'CODE':
  1465. code = lineParser.getToken();
  1466. break;
  1467. case 'VALUE':
  1468. fillColor = lineParser.getToken();
  1469. if ( fillColor.startsWith( '0x' ) ) {
  1470. fillColor = '#' + fillColor.substring( 2 );
  1471. } else if ( ! fillColor.startsWith( '#' ) ) {
  1472. throw new Error( 'LDrawLoader: Invalid color while parsing material' + lineParser.getLineNumberString() + '.' );
  1473. }
  1474. break;
  1475. case 'EDGE':
  1476. edgeColor = lineParser.getToken();
  1477. if ( edgeColor.startsWith( '0x' ) ) {
  1478. edgeColor = '#' + edgeColor.substring( 2 );
  1479. } else if ( ! edgeColor.startsWith( '#' ) ) {
  1480. // Try to see if edge color is a color code
  1481. edgeMaterial = this.getMaterial( edgeColor );
  1482. if ( ! edgeMaterial ) {
  1483. throw new Error( 'LDrawLoader: Invalid edge color while parsing material' + lineParser.getLineNumberString() + '.' );
  1484. }
  1485. // Get the edge material for this triangle material
  1486. edgeMaterial = this.edgeMaterialCache.get( edgeMaterial );
  1487. }
  1488. break;
  1489. case 'ALPHA':
  1490. alpha = parseInt( lineParser.getToken() );
  1491. if ( isNaN( alpha ) ) {
  1492. throw new Error( 'LDrawLoader: Invalid alpha value in material definition' + lineParser.getLineNumberString() + '.' );
  1493. }
  1494. alpha = Math.max( 0, Math.min( 1, alpha / 255 ) );
  1495. if ( alpha < 1 ) {
  1496. isTransparent = true;
  1497. }
  1498. break;
  1499. case 'LUMINANCE':
  1500. if ( ! parseLuminance( lineParser.getToken() ) ) {
  1501. throw new Error( 'LDrawLoader: Invalid luminance value in material definition' + LineParser.getLineNumberString() + '.' );
  1502. }
  1503. break;
  1504. case 'CHROME':
  1505. finishType = FINISH_TYPE_CHROME;
  1506. break;
  1507. case 'PEARLESCENT':
  1508. finishType = FINISH_TYPE_PEARLESCENT;
  1509. break;
  1510. case 'RUBBER':
  1511. finishType = FINISH_TYPE_RUBBER;
  1512. break;
  1513. case 'MATTE_METALLIC':
  1514. finishType = FINISH_TYPE_MATTE_METALLIC;
  1515. break;
  1516. case 'METAL':
  1517. finishType = FINISH_TYPE_METAL;
  1518. break;
  1519. case 'MATERIAL':
  1520. // Not implemented
  1521. lineParser.setToEnd();
  1522. break;
  1523. default:
  1524. throw new Error( 'LDrawLoader: Unknown token "' + token + '" while parsing material' + lineParser.getLineNumberString() + '.' );
  1525. }
  1526. }
  1527. }
  1528. let material = null;
  1529. switch ( finishType ) {
  1530. case FINISH_TYPE_DEFAULT:
  1531. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0 } );
  1532. break;
  1533. case FINISH_TYPE_PEARLESCENT:
  1534. // Try to imitate pearlescency by making the surface glossy
  1535. material = new MeshStandardMaterial( { roughness: 0.3, metalness: 0.25 } );
  1536. break;
  1537. case FINISH_TYPE_CHROME:
  1538. // Mirror finish surface
  1539. material = new MeshStandardMaterial( { roughness: 0, metalness: 1 } );
  1540. break;
  1541. case FINISH_TYPE_RUBBER:
  1542. // Rubber finish
  1543. material = new MeshStandardMaterial( { roughness: 0.9, metalness: 0 } );
  1544. break;
  1545. case FINISH_TYPE_MATTE_METALLIC:
  1546. // Brushed metal finish
  1547. material = new MeshStandardMaterial( { roughness: 0.8, metalness: 0.4 } );
  1548. break;
  1549. case FINISH_TYPE_METAL:
  1550. // Average metal finish
  1551. material = new MeshStandardMaterial( { roughness: 0.2, metalness: 0.85 } );
  1552. break;
  1553. default:
  1554. // Should not happen
  1555. break;
  1556. }
  1557. material.color.setStyle( fillColor, COLOR_SPACE_LDRAW );
  1558. material.transparent = isTransparent;
  1559. material.premultipliedAlpha = true;
  1560. material.opacity = alpha;
  1561. material.depthWrite = ! isTransparent;
  1562. material.polygonOffset = true;
  1563. material.polygonOffsetFactor = 1;
  1564. if ( luminance !== 0 ) {
  1565. material.emissive.setStyle( fillColor, COLOR_SPACE_LDRAW ).multiplyScalar( luminance );
  1566. }
  1567. if ( ! edgeMaterial ) {
  1568. // This is the material used for edges
  1569. edgeMaterial = new LineBasicMaterial( {
  1570. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1571. transparent: isTransparent,
  1572. opacity: alpha,
  1573. depthWrite: ! isTransparent
  1574. } );
  1575. edgeMaterial.color;
  1576. edgeMaterial.userData.code = code;
  1577. edgeMaterial.name = name + ' - Edge';
  1578. if ( this.ConditionalLineMaterial === null ) {
  1579. throw new Error( 'THREE.LDrawLoader: ConditionalLineMaterial type must be specified via .setConditionalLineMaterial().' );
  1580. }
  1581. // This is the material used for conditional edges
  1582. const conditionalEdgeMaterial = new this.ConditionalLineMaterial( {
  1583. fog: true,
  1584. transparent: isTransparent,
  1585. depthWrite: ! isTransparent,
  1586. color: new Color().setStyle( edgeColor, COLOR_SPACE_LDRAW ),
  1587. opacity: alpha,
  1588. } );
  1589. conditionalEdgeMaterial.userData.code = code;
  1590. conditionalEdgeMaterial.name = name + ' - Conditional Edge';
  1591. this.conditionalEdgeMaterialCache.set( edgeMaterial, conditionalEdgeMaterial );
  1592. }
  1593. material.userData.code = code;
  1594. material.name = name;
  1595. this.edgeMaterialCache.set( material, edgeMaterial );
  1596. this.addMaterial( material );
  1597. return material;
  1598. function parseLuminance( token ) {
  1599. // Returns success
  1600. let lum;
  1601. if ( token.startsWith( 'LUMINANCE' ) ) {
  1602. lum = parseInt( token.substring( 9 ) );
  1603. } else {
  1604. lum = parseInt( token );
  1605. }
  1606. if ( isNaN( lum ) ) {
  1607. return false;
  1608. }
  1609. luminance = Math.max( 0, Math.min( 1, lum / 255 ) );
  1610. return true;
  1611. }
  1612. }
  1613. computeBuildingSteps( model ) {
  1614. // Sets userdata.buildingStep number in Group objects and userData.numBuildingSteps number in the root Group object.
  1615. let stepNumber = 0;
  1616. model.traverse( c => {
  1617. if ( c.isGroup ) {
  1618. if ( c.userData.startingBuildingStep ) {
  1619. stepNumber ++;
  1620. }
  1621. c.userData.buildingStep = stepNumber;
  1622. }
  1623. } );
  1624. model.userData.numBuildingSteps = stepNumber + 1;
  1625. }
  1626. }
  1627. export { LDrawLoader };
粤ICP备19079148号