3DMLoader.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  1. import {
  2. BufferGeometryLoader,
  3. CanvasTexture,
  4. ClampToEdgeWrapping,
  5. Color,
  6. DirectionalLight,
  7. DoubleSide,
  8. FileLoader,
  9. LinearFilter,
  10. Line,
  11. LineBasicMaterial,
  12. Loader,
  13. Matrix4,
  14. Mesh,
  15. MeshPhysicalMaterial,
  16. MeshStandardMaterial,
  17. Object3D,
  18. PointLight,
  19. Points,
  20. PointsMaterial,
  21. RectAreaLight,
  22. RepeatWrapping,
  23. SpotLight,
  24. Sprite,
  25. SpriteMaterial,
  26. TextureLoader
  27. } from 'three';
  28. import { EXRLoader } from '../loaders/EXRLoader.js';
  29. const _taskCache = new WeakMap();
  30. /**
  31. * A loader for Rhinoceros 3D files and objects.
  32. *
  33. * Rhinoceros is a 3D modeler used to create, edit, analyze, document, render,
  34. * animate, and translate NURBS curves, surfaces, breps, extrusions, point clouds,
  35. * as well as polygon meshes and SubD objects. `rhino3dm.js` is compiled to WebAssembly
  36. * from the open source geometry library `openNURBS`. The loader currently uses
  37. * `rhino3dm.js 8.4.0`.
  38. *
  39. * ```js
  40. * const loader = new Rhino3dmLoader();
  41. * loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/rhino3dm@8.0.1' );
  42. *
  43. * const object = await loader.loadAsync( 'models/3dm/Rhino_Logo.3dm' );
  44. * scene.add( object );
  45. * ```
  46. *
  47. * @augments Loader
  48. */
  49. class Rhino3dmLoader extends Loader {
  50. /**
  51. * Constructs a new Rhino 3DM loader.
  52. *
  53. * @param {LoadingManager} [manager] - The loading manager.
  54. */
  55. constructor( manager ) {
  56. super( manager );
  57. // internals
  58. this.libraryPath = '';
  59. this.libraryPending = null;
  60. this.libraryBinary = null;
  61. this.libraryConfig = {};
  62. this.url = '';
  63. this.workerLimit = 4;
  64. this.workerPool = [];
  65. this.workerNextTaskID = 1;
  66. this.workerSourceURL = '';
  67. this.workerConfig = {};
  68. this.materials = [];
  69. this.warnings = [];
  70. }
  71. /**
  72. * Path to a folder containing the JS and WASM libraries.
  73. *
  74. * @param {string} path - The library path to set.
  75. * @return {Rhino3dmLoader} A reference to this loader.
  76. */
  77. setLibraryPath( path ) {
  78. this.libraryPath = path;
  79. return this;
  80. }
  81. /**
  82. * Sets the maximum number of Web Workers to be used during decoding.
  83. * A lower limit may be preferable if workers are also for other
  84. * tasks in the application.
  85. *
  86. * @param {number} workerLimit - The worker limit.
  87. * @return {Rhino3dmLoader} A reference to this loader.
  88. */
  89. setWorkerLimit( workerLimit ) {
  90. this.workerLimit = workerLimit;
  91. return this;
  92. }
  93. /**
  94. * Starts loading from the given URL and passes the loaded 3DM asset
  95. * to the `onLoad()` callback.
  96. *
  97. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  98. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  99. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  100. * @param {onErrorCallback} onError - Executed when errors occur.
  101. */
  102. load( url, onLoad, onProgress, onError ) {
  103. const loader = new FileLoader( this.manager );
  104. loader.setPath( this.path );
  105. loader.setResponseType( 'arraybuffer' );
  106. loader.setRequestHeader( this.requestHeader );
  107. this.url = url;
  108. loader.load( url, ( buffer ) => {
  109. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  110. // again from this thread.
  111. if ( _taskCache.has( buffer ) ) {
  112. const cachedTask = _taskCache.get( buffer );
  113. return cachedTask.promise.then( onLoad ).catch( onError );
  114. }
  115. this.decodeObjects( buffer, url )
  116. .then( result => {
  117. result.userData.warnings = this.warnings;
  118. onLoad( result );
  119. } )
  120. .catch( e => onError( e ) );
  121. }, onProgress, onError );
  122. }
  123. /**
  124. * Prints debug messages to the browser console.
  125. */
  126. debug() {
  127. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  128. }
  129. /**
  130. * Decodes the 3DM asset data with a Web Worker.
  131. *
  132. * @param {ArrayBuffer} buffer - The raw 3DM asset data as an array buffer.
  133. * @param {string} url - The asset URL.
  134. * @return {Promise<Object3D>} A Promise that resolved with the decoded 3D object.
  135. */
  136. decodeObjects( buffer, url ) {
  137. let worker;
  138. let taskID;
  139. const taskCost = buffer.byteLength;
  140. const objectPending = this._getWorker( taskCost )
  141. .then( ( _worker ) => {
  142. worker = _worker;
  143. taskID = this.workerNextTaskID ++;
  144. return new Promise( ( resolve, reject ) => {
  145. worker._callbacks[ taskID ] = { resolve, reject };
  146. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  147. // this.debug();
  148. } );
  149. } )
  150. .then( ( message ) => this._createGeometry( message.data ) )
  151. .catch( e => {
  152. throw e;
  153. } );
  154. // Remove task from the task list.
  155. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  156. objectPending
  157. .catch( () => true )
  158. .then( () => {
  159. if ( worker && taskID ) {
  160. this._releaseTask( worker, taskID );
  161. //this.debug();
  162. }
  163. } );
  164. // Cache the task result.
  165. _taskCache.set( buffer, {
  166. url: url,
  167. promise: objectPending
  168. } );
  169. return objectPending;
  170. }
  171. /**
  172. * Parses the given 3DM data and passes the loaded 3DM asset
  173. * to the `onLoad()` callback.
  174. *
  175. * @param {ArrayBuffer} data - The raw 3DM asset data as an array buffer.
  176. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  177. * @param {onErrorCallback} onError - Executed when errors occur.
  178. */
  179. parse( data, onLoad, onError ) {
  180. this.decodeObjects( data, '' )
  181. .then( result => {
  182. result.userData.warnings = this.warnings;
  183. onLoad( result );
  184. } )
  185. .catch( e => onError( e ) );
  186. }
  187. _compareMaterials( material ) {
  188. const mat = {};
  189. mat.name = material.name;
  190. mat.color = {};
  191. mat.color.r = material.color.r;
  192. mat.color.g = material.color.g;
  193. mat.color.b = material.color.b;
  194. mat.type = material.type;
  195. mat.vertexColors = material.vertexColors;
  196. const json = JSON.stringify( mat );
  197. for ( let i = 0; i < this.materials.length; i ++ ) {
  198. const m = this.materials[ i ];
  199. const _mat = {};
  200. _mat.name = m.name;
  201. _mat.color = {};
  202. _mat.color.r = m.color.r;
  203. _mat.color.g = m.color.g;
  204. _mat.color.b = m.color.b;
  205. _mat.type = m.type;
  206. _mat.vertexColors = m.vertexColors;
  207. if ( JSON.stringify( _mat ) === json ) {
  208. return m;
  209. }
  210. }
  211. this.materials.push( material );
  212. return material;
  213. }
  214. _createMaterial( material, renderEnvironment ) {
  215. if ( material === undefined ) {
  216. return new MeshStandardMaterial( {
  217. color: new Color( 1, 1, 1 ),
  218. metalness: 0.8,
  219. name: Loader.DEFAULT_MATERIAL_NAME,
  220. side: DoubleSide
  221. } );
  222. }
  223. //console.log(material)
  224. const mat = new MeshPhysicalMaterial( {
  225. color: new Color( material.diffuseColor.r / 255.0, material.diffuseColor.g / 255.0, material.diffuseColor.b / 255.0 ),
  226. emissive: new Color( material.emissionColor.r, material.emissionColor.g, material.emissionColor.b ),
  227. flatShading: material.disableLighting,
  228. ior: material.indexOfRefraction,
  229. name: material.name,
  230. reflectivity: material.reflectivity,
  231. opacity: 1.0 - material.transparency,
  232. side: DoubleSide,
  233. specularColor: material.specularColor,
  234. transparent: material.transparency > 0 ? true : false
  235. } );
  236. mat.userData.id = material.id;
  237. if ( material.pbrSupported ) {
  238. const pbr = material.pbr;
  239. mat.anisotropy = pbr.anisotropic;
  240. mat.anisotropyRotation = pbr.anisotropicRotation;
  241. mat.color = new Color( pbr.baseColor.r, pbr.baseColor.g, pbr.baseColor.b );
  242. mat.clearcoat = pbr.clearcoat;
  243. mat.clearcoatRoughness = pbr.clearcoatRoughness;
  244. mat.metalness = pbr.metallic;
  245. mat.transmission = 1 - pbr.opacity;
  246. mat.roughness = pbr.roughness;
  247. mat.sheen = pbr.sheen;
  248. mat.specularIntensity = pbr.specular;
  249. mat.thickness = pbr.subsurface;
  250. }
  251. if ( material.pbrSupported && material.pbr.opacity === 0 && material.transparency === 1 ) {
  252. //some compromises
  253. mat.opacity = 0.2;
  254. mat.transmission = 1.00;
  255. }
  256. const textureLoader = new TextureLoader();
  257. for ( let i = 0; i < material.textures.length; i ++ ) {
  258. const texture = material.textures[ i ];
  259. if ( texture.image !== null ) {
  260. const map = textureLoader.load( texture.image );
  261. //console.log(texture.type )
  262. switch ( texture.type ) {
  263. case 'Bump':
  264. mat.bumpMap = map;
  265. break;
  266. case 'Diffuse':
  267. mat.map = map;
  268. break;
  269. case 'Emap':
  270. mat.envMap = map;
  271. break;
  272. case 'Opacity':
  273. mat.transmissionMap = map;
  274. break;
  275. case 'Transparency':
  276. mat.alphaMap = map;
  277. mat.transparent = true;
  278. break;
  279. case 'PBR_Alpha':
  280. mat.alphaMap = map;
  281. mat.transparent = true;
  282. break;
  283. case 'PBR_AmbientOcclusion':
  284. mat.aoMap = map;
  285. break;
  286. case 'PBR_Anisotropic':
  287. mat.anisotropyMap = map;
  288. break;
  289. case 'PBR_BaseColor':
  290. mat.map = map;
  291. break;
  292. case 'PBR_Clearcoat':
  293. mat.clearcoatMap = map;
  294. break;
  295. case 'PBR_ClearcoatBump':
  296. mat.clearcoatNormalMap = map;
  297. break;
  298. case 'PBR_ClearcoatRoughness':
  299. mat.clearcoatRoughnessMap = map;
  300. break;
  301. case 'PBR_Displacement':
  302. mat.displacementMap = map;
  303. break;
  304. case 'PBR_Emission':
  305. mat.emissiveMap = map;
  306. break;
  307. case 'PBR_Metallic':
  308. mat.metalnessMap = map;
  309. break;
  310. case 'PBR_Roughness':
  311. mat.roughnessMap = map;
  312. break;
  313. case 'PBR_Sheen':
  314. mat.sheenColorMap = map;
  315. break;
  316. case 'PBR_Specular':
  317. mat.specularColorMap = map;
  318. break;
  319. case 'PBR_Subsurface':
  320. mat.thicknessMap = map;
  321. break;
  322. default:
  323. this.warnings.push( {
  324. message: `THREE.3DMLoader: No conversion exists for 3dm ${texture.type}.`,
  325. type: 'no conversion'
  326. } );
  327. break;
  328. }
  329. map.wrapS = texture.wrapU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  330. map.wrapT = texture.wrapV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  331. if ( texture.repeat ) {
  332. map.repeat.set( texture.repeat[ 0 ], texture.repeat[ 1 ] );
  333. }
  334. }
  335. }
  336. if ( renderEnvironment ) {
  337. new EXRLoader().load( renderEnvironment.image, function ( texture ) {
  338. texture.mapping = THREE.EquirectangularReflectionMapping;
  339. mat.envMap = texture;
  340. } );
  341. }
  342. return mat;
  343. }
  344. _createGeometry( data ) {
  345. const object = new Object3D();
  346. const instanceDefinitionObjects = [];
  347. const instanceDefinitions = [];
  348. const instanceReferences = [];
  349. object.userData[ 'layers' ] = data.layers;
  350. object.userData[ 'groups' ] = data.groups;
  351. object.userData[ 'settings' ] = data.settings;
  352. object.userData.settings[ 'renderSettings' ] = data.renderSettings;
  353. object.userData[ 'objectType' ] = 'File3dm';
  354. object.userData[ 'materials' ] = null;
  355. object.name = this.url;
  356. let objects = data.objects;
  357. const materials = data.materials;
  358. for ( let i = 0; i < objects.length; i ++ ) {
  359. const obj = objects[ i ];
  360. const attributes = obj.attributes;
  361. switch ( obj.objectType ) {
  362. case 'InstanceDefinition':
  363. instanceDefinitions.push( obj );
  364. break;
  365. case 'InstanceReference':
  366. instanceReferences.push( obj );
  367. break;
  368. default:
  369. let matId = null;
  370. switch ( attributes.materialSource.name ) {
  371. case 'ObjectMaterialSource_MaterialFromLayer':
  372. //check layer index
  373. if ( attributes.layerIndex >= 0 ) {
  374. matId = data.layers[ attributes.layerIndex ].renderMaterialIndex;
  375. }
  376. break;
  377. case 'ObjectMaterialSource_MaterialFromObject':
  378. if ( attributes.materialIndex >= 0 ) {
  379. matId = attributes.materialIndex;
  380. }
  381. break;
  382. }
  383. let material = null;
  384. if ( matId >= 0 ) {
  385. const rMaterial = materials[ matId ];
  386. material = this._createMaterial( rMaterial, data.renderEnvironment );
  387. }
  388. const _object = this._createObject( obj, material );
  389. if ( _object === undefined ) {
  390. continue;
  391. }
  392. const layer = data.layers[ attributes.layerIndex ];
  393. _object.visible = layer ? data.layers[ attributes.layerIndex ].visible : true;
  394. if ( attributes.isInstanceDefinitionObject ) {
  395. instanceDefinitionObjects.push( _object );
  396. } else {
  397. object.add( _object );
  398. }
  399. break;
  400. }
  401. }
  402. for ( let i = 0; i < instanceDefinitions.length; i ++ ) {
  403. const iDef = instanceDefinitions[ i ];
  404. objects = [];
  405. for ( let j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  406. const objId = iDef.attributes.objectIds[ j ];
  407. for ( let p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  408. const idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  409. if ( objId === idoId ) {
  410. objects.push( instanceDefinitionObjects[ p ] );
  411. }
  412. }
  413. }
  414. // Currently clones geometry and does not take advantage of instancing
  415. for ( let j = 0; j < instanceReferences.length; j ++ ) {
  416. const iRef = instanceReferences[ j ];
  417. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  418. const iRefObject = new Object3D();
  419. const xf = iRef.geometry.xform.array;
  420. const matrix = new Matrix4();
  421. matrix.set( ...xf );
  422. iRefObject.applyMatrix4( matrix );
  423. for ( let p = 0; p < objects.length; p ++ ) {
  424. iRefObject.add( objects[ p ].clone( true ) );
  425. }
  426. object.add( iRefObject );
  427. }
  428. }
  429. }
  430. object.userData[ 'materials' ] = this.materials;
  431. object.name = '';
  432. return object;
  433. }
  434. _createObject( obj, mat ) {
  435. const loader = new BufferGeometryLoader();
  436. const attributes = obj.attributes;
  437. let geometry, material, _color, color;
  438. switch ( obj.objectType ) {
  439. case 'Point':
  440. case 'PointSet':
  441. geometry = loader.parse( obj.geometry );
  442. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  443. material = new PointsMaterial( { vertexColors: true, sizeAttenuation: false, size: 2 } );
  444. } else {
  445. _color = attributes.drawColor;
  446. color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  447. material = new PointsMaterial( { color: color, sizeAttenuation: false, size: 2 } );
  448. }
  449. material = this._compareMaterials( material );
  450. const points = new Points( geometry, material );
  451. points.userData[ 'attributes' ] = attributes;
  452. points.userData[ 'objectType' ] = obj.objectType;
  453. if ( attributes.name ) {
  454. points.name = attributes.name;
  455. }
  456. return points;
  457. case 'Mesh':
  458. case 'Extrusion':
  459. case 'SubD':
  460. case 'Brep':
  461. if ( obj.geometry === null ) return;
  462. geometry = loader.parse( obj.geometry );
  463. if ( mat === null ) {
  464. mat = this._createMaterial();
  465. }
  466. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  467. mat.vertexColors = true;
  468. }
  469. mat = this._compareMaterials( mat );
  470. const mesh = new Mesh( geometry, mat );
  471. mesh.castShadow = attributes.castsShadows;
  472. mesh.receiveShadow = attributes.receivesShadows;
  473. mesh.userData[ 'attributes' ] = attributes;
  474. mesh.userData[ 'objectType' ] = obj.objectType;
  475. if ( attributes.name ) {
  476. mesh.name = attributes.name;
  477. }
  478. return mesh;
  479. case 'Curve':
  480. geometry = loader.parse( obj.geometry );
  481. _color = attributes.drawColor;
  482. color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  483. material = new LineBasicMaterial( { color: color } );
  484. material = this._compareMaterials( material );
  485. const lines = new Line( geometry, material );
  486. lines.userData[ 'attributes' ] = attributes;
  487. lines.userData[ 'objectType' ] = obj.objectType;
  488. if ( attributes.name ) {
  489. lines.name = attributes.name;
  490. }
  491. return lines;
  492. case 'TextDot':
  493. geometry = obj.geometry;
  494. const ctx = document.createElement( 'canvas' ).getContext( '2d' );
  495. const font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  496. ctx.font = font;
  497. const width = ctx.measureText( geometry.text ).width + 10;
  498. const height = geometry.fontHeight + 10;
  499. const r = window.devicePixelRatio;
  500. ctx.canvas.width = width * r;
  501. ctx.canvas.height = height * r;
  502. ctx.canvas.style.width = width + 'px';
  503. ctx.canvas.style.height = height + 'px';
  504. ctx.setTransform( r, 0, 0, r, 0, 0 );
  505. ctx.font = font;
  506. ctx.textBaseline = 'middle';
  507. ctx.textAlign = 'center';
  508. color = attributes.drawColor;
  509. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  510. ctx.fillRect( 0, 0, width, height );
  511. ctx.fillStyle = 'white';
  512. ctx.fillText( geometry.text, width / 2, height / 2 );
  513. const texture = new CanvasTexture( ctx.canvas );
  514. texture.minFilter = LinearFilter;
  515. texture.generateMipmaps = false;
  516. texture.wrapS = ClampToEdgeWrapping;
  517. texture.wrapT = ClampToEdgeWrapping;
  518. material = new SpriteMaterial( { map: texture, depthTest: false } );
  519. const sprite = new Sprite( material );
  520. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  521. sprite.scale.set( width / 10, height / 10, 1.0 );
  522. sprite.userData[ 'attributes' ] = attributes;
  523. sprite.userData[ 'objectType' ] = obj.objectType;
  524. if ( attributes.name ) {
  525. sprite.name = attributes.name;
  526. }
  527. return sprite;
  528. case 'Light':
  529. geometry = obj.geometry;
  530. let light;
  531. switch ( geometry.lightStyle.name ) {
  532. case 'LightStyle_WorldPoint':
  533. light = new PointLight();
  534. light.castShadow = attributes.castsShadows;
  535. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  536. light.shadow.normalBias = 0.1;
  537. break;
  538. case 'LightStyle_WorldSpot':
  539. light = new SpotLight();
  540. light.castShadow = attributes.castsShadows;
  541. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  542. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  543. light.angle = geometry.spotAngleRadians;
  544. light.shadow.normalBias = 0.1;
  545. break;
  546. case 'LightStyle_WorldRectangular':
  547. light = new RectAreaLight();
  548. const width = Math.abs( geometry.width[ 2 ] );
  549. const height = Math.abs( geometry.length[ 0 ] );
  550. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  551. light.height = height;
  552. light.width = width;
  553. light.lookAt( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  554. break;
  555. case 'LightStyle_WorldDirectional':
  556. light = new DirectionalLight();
  557. light.castShadow = attributes.castsShadows;
  558. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  559. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  560. light.shadow.normalBias = 0.1;
  561. break;
  562. case 'LightStyle_WorldLinear':
  563. // no conversion exists, warning has already been printed to the console
  564. break;
  565. default:
  566. break;
  567. }
  568. if ( light ) {
  569. light.intensity = geometry.intensity;
  570. _color = geometry.diffuse;
  571. color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  572. light.color = color;
  573. light.userData[ 'attributes' ] = attributes;
  574. light.userData[ 'objectType' ] = obj.objectType;
  575. }
  576. return light;
  577. }
  578. }
  579. _initLibrary() {
  580. if ( ! this.libraryPending ) {
  581. // Load rhino3dm wrapper.
  582. const jsLoader = new FileLoader( this.manager );
  583. jsLoader.setPath( this.libraryPath );
  584. const jsContent = new Promise( ( resolve, reject ) => {
  585. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  586. } );
  587. // Load rhino3dm WASM binary.
  588. const binaryLoader = new FileLoader( this.manager );
  589. binaryLoader.setPath( this.libraryPath );
  590. binaryLoader.setResponseType( 'arraybuffer' );
  591. const binaryContent = new Promise( ( resolve, reject ) => {
  592. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  593. } );
  594. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  595. .then( ( [ jsContent, binaryContent ] ) => {
  596. //this.libraryBinary = binaryContent;
  597. this.libraryConfig.wasmBinary = binaryContent;
  598. const fn = Rhino3dmWorker.toString();
  599. const body = [
  600. '/* rhino3dm.js */',
  601. jsContent,
  602. '/* worker */',
  603. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  604. ].join( '\n' );
  605. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  606. } );
  607. }
  608. return this.libraryPending;
  609. }
  610. _getWorker( taskCost ) {
  611. return this._initLibrary().then( () => {
  612. if ( this.workerPool.length < this.workerLimit ) {
  613. const worker = new Worker( this.workerSourceURL );
  614. worker._callbacks = {};
  615. worker._taskCosts = {};
  616. worker._taskLoad = 0;
  617. worker.postMessage( {
  618. type: 'init',
  619. libraryConfig: this.libraryConfig
  620. } );
  621. worker.onmessage = e => {
  622. const message = e.data;
  623. switch ( message.type ) {
  624. case 'warning':
  625. this.warnings.push( message.data );
  626. console.warn( message.data );
  627. break;
  628. case 'decode':
  629. worker._callbacks[ message.id ].resolve( message );
  630. break;
  631. case 'error':
  632. worker._callbacks[ message.id ].reject( message );
  633. break;
  634. default:
  635. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  636. }
  637. };
  638. this.workerPool.push( worker );
  639. } else {
  640. this.workerPool.sort( function ( a, b ) {
  641. return a._taskLoad > b._taskLoad ? - 1 : 1;
  642. } );
  643. }
  644. const worker = this.workerPool[ this.workerPool.length - 1 ];
  645. worker._taskLoad += taskCost;
  646. return worker;
  647. } );
  648. }
  649. _releaseTask( worker, taskID ) {
  650. worker._taskLoad -= worker._taskCosts[ taskID ];
  651. delete worker._callbacks[ taskID ];
  652. delete worker._taskCosts[ taskID ];
  653. }
  654. /**
  655. * Frees internal resources. This method should be called
  656. * when the loader is no longer required.
  657. */
  658. dispose() {
  659. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  660. this.workerPool[ i ].terminate();
  661. }
  662. this.workerPool.length = 0;
  663. }
  664. }
  665. /* WEB WORKER */
  666. function Rhino3dmWorker() {
  667. let libraryPending;
  668. let libraryConfig;
  669. let rhino;
  670. let taskID;
  671. onmessage = function ( e ) {
  672. const message = e.data;
  673. switch ( message.type ) {
  674. case 'init':
  675. libraryConfig = message.libraryConfig;
  676. const wasmBinary = libraryConfig.wasmBinary;
  677. let RhinoModule;
  678. libraryPending = new Promise( function ( resolve ) {
  679. /* Like Basis Loader */
  680. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  681. rhino3dm( RhinoModule ); // eslint-disable-line no-undef
  682. } ).then( () => {
  683. rhino = RhinoModule;
  684. } );
  685. break;
  686. case 'decode':
  687. taskID = message.id;
  688. const buffer = message.buffer;
  689. libraryPending.then( () => {
  690. try {
  691. const data = decodeObjects( rhino, buffer );
  692. self.postMessage( { type: 'decode', id: message.id, data } );
  693. } catch ( error ) {
  694. self.postMessage( { type: 'error', id: message.id, error } );
  695. }
  696. } );
  697. break;
  698. }
  699. };
  700. function decodeObjects( rhino, buffer ) {
  701. const arr = new Uint8Array( buffer );
  702. const doc = rhino.File3dm.fromByteArray( arr );
  703. const objects = [];
  704. const materials = [];
  705. const layers = [];
  706. const views = [];
  707. const namedViews = [];
  708. const groups = [];
  709. const strings = [];
  710. //Handle objects
  711. const objs = doc.objects();
  712. const cnt = objs.count;
  713. for ( let i = 0; i < cnt; i ++ ) {
  714. const _object = objs.get( i );
  715. const object = extractObjectData( _object, doc );
  716. _object.delete();
  717. if ( object ) {
  718. objects.push( object );
  719. }
  720. }
  721. // Handle instance definitions
  722. // console.log( `Instance Definitions Count: ${doc.instanceDefinitions().count()}` );
  723. for ( let i = 0; i < doc.instanceDefinitions().count; i ++ ) {
  724. const idef = doc.instanceDefinitions().get( i );
  725. const idefAttributes = extractProperties( idef );
  726. idefAttributes.objectIds = idef.getObjectIds();
  727. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  728. }
  729. // Handle materials
  730. const textureTypes = [
  731. // rhino.TextureType.Bitmap,
  732. rhino.TextureType.Diffuse,
  733. rhino.TextureType.Bump,
  734. rhino.TextureType.Transparency,
  735. rhino.TextureType.Opacity,
  736. rhino.TextureType.Emap
  737. ];
  738. const pbrTextureTypes = [
  739. rhino.TextureType.PBR_BaseColor,
  740. rhino.TextureType.PBR_Subsurface,
  741. rhino.TextureType.PBR_SubsurfaceScattering,
  742. rhino.TextureType.PBR_SubsurfaceScatteringRadius,
  743. rhino.TextureType.PBR_Metallic,
  744. rhino.TextureType.PBR_Specular,
  745. rhino.TextureType.PBR_SpecularTint,
  746. rhino.TextureType.PBR_Roughness,
  747. rhino.TextureType.PBR_Anisotropic,
  748. rhino.TextureType.PBR_Anisotropic_Rotation,
  749. rhino.TextureType.PBR_Sheen,
  750. rhino.TextureType.PBR_SheenTint,
  751. rhino.TextureType.PBR_Clearcoat,
  752. rhino.TextureType.PBR_ClearcoatBump,
  753. rhino.TextureType.PBR_ClearcoatRoughness,
  754. rhino.TextureType.PBR_OpacityIor,
  755. rhino.TextureType.PBR_OpacityRoughness,
  756. rhino.TextureType.PBR_Emission,
  757. rhino.TextureType.PBR_AmbientOcclusion,
  758. rhino.TextureType.PBR_Displacement
  759. ];
  760. for ( let i = 0; i < doc.materials().count; i ++ ) {
  761. const _material = doc.materials().get( i );
  762. const material = extractProperties( _material );
  763. const textures = [];
  764. textures.push( ...extractTextures( _material, textureTypes, doc ) );
  765. material.pbrSupported = _material.physicallyBased().supported;
  766. if ( material.pbrSupported ) {
  767. textures.push( ...extractTextures( _material, pbrTextureTypes, doc ) );
  768. material.pbr = extractProperties( _material.physicallyBased() );
  769. }
  770. material.textures = textures;
  771. materials.push( material );
  772. _material.delete();
  773. }
  774. // Handle layers
  775. for ( let i = 0; i < doc.layers().count; i ++ ) {
  776. const _layer = doc.layers().get( i );
  777. const layer = extractProperties( _layer );
  778. layers.push( layer );
  779. _layer.delete();
  780. }
  781. // Handle views
  782. for ( let i = 0; i < doc.views().count; i ++ ) {
  783. const _view = doc.views().get( i );
  784. const view = extractProperties( _view );
  785. views.push( view );
  786. _view.delete();
  787. }
  788. // Handle named views
  789. for ( let i = 0; i < doc.namedViews().count; i ++ ) {
  790. const _namedView = doc.namedViews().get( i );
  791. const namedView = extractProperties( _namedView );
  792. namedViews.push( namedView );
  793. _namedView.delete();
  794. }
  795. // Handle groups
  796. for ( let i = 0; i < doc.groups().count; i ++ ) {
  797. const _group = doc.groups().get( i );
  798. const group = extractProperties( _group );
  799. groups.push( group );
  800. _group.delete();
  801. }
  802. // Handle settings
  803. const settings = extractProperties( doc.settings() );
  804. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  805. // Handle dimstyles
  806. // console.log( `Dimstyle Count: ${doc.dimstyles().count()}` );
  807. // Handle bitmaps
  808. // console.log( `Bitmap Count: ${doc.bitmaps().count()}` );
  809. // Handle strings
  810. // console.log( `Document Strings Count: ${doc.strings().count()}` );
  811. // Note: doc.strings().documentUserTextCount() counts any doc.strings defined in a section
  812. // console.log( `Document User Text Count: ${doc.strings().documentUserTextCount()}` );
  813. const strings_count = doc.strings().count;
  814. for ( let i = 0; i < strings_count; i ++ ) {
  815. strings.push( doc.strings().get( i ) );
  816. }
  817. // Handle Render Environments for Material Environment
  818. // get the id of the active render environment skylight, which we'll use for environment texture
  819. const reflectionId = doc.settings().renderSettings().renderEnvironments.reflectionId;
  820. const rc = doc.renderContent();
  821. let renderEnvironment = null;
  822. for ( let i = 0; i < rc.count; i ++ ) {
  823. const content = rc.get( i );
  824. switch ( content.kind ) {
  825. case 'environment':
  826. const id = content.id;
  827. // there could be multiple render environments in a 3dm file
  828. if ( id !== reflectionId ) break;
  829. const renderTexture = content.findChild( 'texture' );
  830. const fileName = renderTexture.fileName;
  831. for ( let j = 0; j < doc.embeddedFiles().count; j ++ ) {
  832. const _fileName = doc.embeddedFiles().get( j ).fileName;
  833. if ( fileName === _fileName ) {
  834. const background = doc.getEmbeddedFileAsBase64( fileName );
  835. const backgroundImage = 'data:image/png;base64,' + background;
  836. renderEnvironment = { type: 'renderEnvironment', image: backgroundImage, name: fileName };
  837. }
  838. }
  839. break;
  840. }
  841. }
  842. // Handle Render Settings
  843. const renderSettings = {
  844. ambientLight: doc.settings().renderSettings().ambientLight,
  845. backgroundColorTop: doc.settings().renderSettings().backgroundColorTop,
  846. backgroundColorBottom: doc.settings().renderSettings().backgroundColorBottom,
  847. useHiddenLights: doc.settings().renderSettings().useHiddenLights,
  848. depthCue: doc.settings().renderSettings().depthCue,
  849. flatShade: doc.settings().renderSettings().flatShade,
  850. renderBackFaces: doc.settings().renderSettings().renderBackFaces,
  851. renderPoints: doc.settings().renderSettings().renderPoints,
  852. renderCurves: doc.settings().renderSettings().renderCurves,
  853. renderIsoParams: doc.settings().renderSettings().renderIsoParams,
  854. renderMeshEdges: doc.settings().renderSettings().renderMeshEdges,
  855. renderAnnotations: doc.settings().renderSettings().renderAnnotations,
  856. useViewportSize: doc.settings().renderSettings().useViewportSize,
  857. scaleBackgroundToFit: doc.settings().renderSettings().scaleBackgroundToFit,
  858. transparentBackground: doc.settings().renderSettings().transparentBackground,
  859. imageDpi: doc.settings().renderSettings().imageDpi,
  860. shadowMapLevel: doc.settings().renderSettings().shadowMapLevel,
  861. namedView: doc.settings().renderSettings().namedView,
  862. snapShot: doc.settings().renderSettings().snapShot,
  863. specificViewport: doc.settings().renderSettings().specificViewport,
  864. groundPlane: extractProperties( doc.settings().renderSettings().groundPlane ),
  865. safeFrame: extractProperties( doc.settings().renderSettings().safeFrame ),
  866. dithering: extractProperties( doc.settings().renderSettings().dithering ),
  867. skylight: extractProperties( doc.settings().renderSettings().skylight ),
  868. linearWorkflow: extractProperties( doc.settings().renderSettings().linearWorkflow ),
  869. renderChannels: extractProperties( doc.settings().renderSettings().renderChannels ),
  870. sun: extractProperties( doc.settings().renderSettings().sun ),
  871. renderEnvironments: extractProperties( doc.settings().renderSettings().renderEnvironments ),
  872. postEffects: extractProperties( doc.settings().renderSettings().postEffects ),
  873. };
  874. doc.delete();
  875. return { objects, materials, layers, views, namedViews, groups, strings, settings, renderSettings, renderEnvironment };
  876. }
  877. function extractTextures( m, tTypes, d ) {
  878. const textures = [];
  879. for ( let i = 0; i < tTypes.length; i ++ ) {
  880. const _texture = m.getTexture( tTypes[ i ] );
  881. if ( _texture ) {
  882. let textureType = tTypes[ i ].constructor.name;
  883. textureType = textureType.substring( 12, textureType.length );
  884. const texture = extractTextureData( _texture, textureType, d );
  885. textures.push( texture );
  886. _texture.delete();
  887. }
  888. }
  889. return textures;
  890. }
  891. function extractTextureData( t, tType, d ) {
  892. const texture = { type: tType };
  893. const image = d.getEmbeddedFileAsBase64( t.fileName );
  894. texture.wrapU = t.wrapU;
  895. texture.wrapV = t.wrapV;
  896. texture.wrapW = t.wrapW;
  897. const uvw = t.uvwTransform.toFloatArray( true );
  898. texture.repeat = [ uvw[ 0 ], uvw[ 5 ] ];
  899. if ( image ) {
  900. texture.image = 'data:image/png;base64,' + image;
  901. } else {
  902. self.postMessage( { type: 'warning', id: taskID, data: {
  903. message: `THREE.3DMLoader: Image for ${tType} texture not embedded in file.`,
  904. type: 'missing resource'
  905. }
  906. } );
  907. texture.image = null;
  908. }
  909. return texture;
  910. }
  911. function extractObjectData( object, doc ) {
  912. const _geometry = object.geometry();
  913. const _attributes = object.attributes();
  914. let objectType = _geometry.objectType;
  915. let geometry, attributes, position, data, mesh;
  916. // skip instance definition objects
  917. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  918. // TODO: handle other geometry types
  919. switch ( objectType ) {
  920. case rhino.ObjectType.Curve:
  921. const pts = curveToPoints( _geometry, 100 );
  922. position = {};
  923. attributes = {};
  924. data = {};
  925. position.itemSize = 3;
  926. position.type = 'Float32Array';
  927. position.array = [];
  928. for ( let j = 0; j < pts.length; j ++ ) {
  929. position.array.push( pts[ j ][ 0 ] );
  930. position.array.push( pts[ j ][ 1 ] );
  931. position.array.push( pts[ j ][ 2 ] );
  932. }
  933. attributes.position = position;
  934. data.attributes = attributes;
  935. geometry = { data };
  936. break;
  937. case rhino.ObjectType.Point:
  938. const pt = _geometry.location;
  939. position = {};
  940. const color = {};
  941. attributes = {};
  942. data = {};
  943. position.itemSize = 3;
  944. position.type = 'Float32Array';
  945. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  946. const _color = _attributes.drawColor( doc );
  947. color.itemSize = 3;
  948. color.type = 'Float32Array';
  949. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  950. attributes.position = position;
  951. attributes.color = color;
  952. data.attributes = attributes;
  953. geometry = { data };
  954. break;
  955. case rhino.ObjectType.PointSet:
  956. case rhino.ObjectType.Mesh:
  957. geometry = _geometry.toThreejsJSON();
  958. break;
  959. case rhino.ObjectType.Brep:
  960. const faces = _geometry.faces();
  961. mesh = new rhino.Mesh();
  962. for ( let faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  963. const face = faces.get( faceIndex );
  964. const _mesh = face.getMesh( rhino.MeshType.Any );
  965. if ( _mesh ) {
  966. mesh.append( _mesh );
  967. _mesh.delete();
  968. }
  969. face.delete();
  970. }
  971. if ( mesh.faces().count > 0 ) {
  972. mesh.compact();
  973. geometry = mesh.toThreejsJSON();
  974. faces.delete();
  975. }
  976. mesh.delete();
  977. break;
  978. case rhino.ObjectType.Extrusion:
  979. mesh = _geometry.getMesh( rhino.MeshType.Any );
  980. if ( mesh ) {
  981. geometry = mesh.toThreejsJSON();
  982. mesh.delete();
  983. }
  984. break;
  985. case rhino.ObjectType.TextDot:
  986. geometry = extractProperties( _geometry );
  987. break;
  988. case rhino.ObjectType.Light:
  989. geometry = extractProperties( _geometry );
  990. if ( geometry.lightStyle.name === 'LightStyle_WorldLinear' ) {
  991. self.postMessage( { type: 'warning', id: taskID, data: {
  992. message: `THREE.3DMLoader: No conversion exists for ${objectType.constructor.name} ${geometry.lightStyle.name}`,
  993. type: 'no conversion',
  994. guid: _attributes.id
  995. }
  996. } );
  997. }
  998. break;
  999. case rhino.ObjectType.InstanceReference:
  1000. geometry = extractProperties( _geometry );
  1001. geometry.xform = extractProperties( _geometry.xform );
  1002. geometry.xform.array = _geometry.xform.toFloatArray( true );
  1003. break;
  1004. case rhino.ObjectType.SubD:
  1005. // TODO: precalculate resulting vertices and faces and warn on excessive results
  1006. _geometry.subdivide( 3 );
  1007. mesh = rhino.Mesh.createFromSubDControlNet( _geometry, false );
  1008. if ( mesh ) {
  1009. geometry = mesh.toThreejsJSON();
  1010. mesh.delete();
  1011. }
  1012. break;
  1013. /*
  1014. case rhino.ObjectType.Annotation:
  1015. case rhino.ObjectType.Hatch:
  1016. case rhino.ObjectType.ClipPlane:
  1017. */
  1018. default:
  1019. self.postMessage( { type: 'warning', id: taskID, data: {
  1020. message: `THREE.3DMLoader: Conversion not implemented for ${objectType.constructor.name}`,
  1021. type: 'not implemented',
  1022. guid: _attributes.id
  1023. }
  1024. } );
  1025. break;
  1026. }
  1027. if ( geometry ) {
  1028. attributes = extractProperties( _attributes );
  1029. attributes.geometry = extractProperties( _geometry );
  1030. if ( _attributes.groupCount > 0 ) {
  1031. attributes.groupIds = _attributes.getGroupList();
  1032. }
  1033. if ( _attributes.userStringCount > 0 ) {
  1034. attributes.userStrings = _attributes.getUserStrings();
  1035. }
  1036. if ( _geometry.userStringCount > 0 ) {
  1037. attributes.geometry.userStrings = _geometry.getUserStrings();
  1038. }
  1039. if ( _attributes.decals().count > 0 ) {
  1040. self.postMessage( { type: 'warning', id: taskID, data: {
  1041. message: 'THREE.3DMLoader: No conversion exists for the decals associated with this object.',
  1042. type: 'no conversion',
  1043. guid: _attributes.id
  1044. }
  1045. } );
  1046. }
  1047. attributes.drawColor = _attributes.drawColor( doc );
  1048. objectType = objectType.constructor.name;
  1049. objectType = objectType.substring( 11, objectType.length );
  1050. return { geometry, attributes, objectType };
  1051. } else {
  1052. self.postMessage( { type: 'warning', id: taskID, data: {
  1053. message: `THREE.3DMLoader: ${objectType.constructor.name} has no associated mesh geometry.`,
  1054. type: 'missing mesh',
  1055. guid: _attributes.id
  1056. }
  1057. } );
  1058. }
  1059. }
  1060. function extractProperties( object ) {
  1061. const result = {};
  1062. for ( const property in object ) {
  1063. const value = object[ property ];
  1064. if ( typeof value !== 'function' ) {
  1065. if ( typeof value === 'object' && value !== null && value.hasOwnProperty( 'constructor' ) ) {
  1066. result[ property ] = { name: value.constructor.name, value: value.value };
  1067. } else if ( typeof value === 'object' && value !== null ) {
  1068. result[ property ] = extractProperties( value );
  1069. } else {
  1070. result[ property ] = value;
  1071. }
  1072. } else {
  1073. // these are functions that could be called to extract more data.
  1074. //console.log( `${property}: ${object[ property ].constructor.name}` );
  1075. }
  1076. }
  1077. return result;
  1078. }
  1079. function curveToPoints( curve, pointLimit ) {
  1080. let pointCount = pointLimit;
  1081. let rc = [];
  1082. const ts = [];
  1083. if ( curve instanceof rhino.LineCurve ) {
  1084. return [ curve.pointAtStart, curve.pointAtEnd ];
  1085. }
  1086. if ( curve instanceof rhino.PolylineCurve ) {
  1087. pointCount = curve.pointCount;
  1088. for ( let i = 0; i < pointCount; i ++ ) {
  1089. rc.push( curve.point( i ) );
  1090. }
  1091. return rc;
  1092. }
  1093. if ( curve instanceof rhino.PolyCurve ) {
  1094. const segmentCount = curve.segmentCount;
  1095. for ( let i = 0; i < segmentCount; i ++ ) {
  1096. const segment = curve.segmentCurve( i );
  1097. const segmentArray = curveToPoints( segment, pointCount );
  1098. rc = rc.concat( segmentArray );
  1099. segment.delete();
  1100. }
  1101. return rc;
  1102. }
  1103. if ( curve instanceof rhino.ArcCurve ) {
  1104. pointCount = Math.floor( curve.angleDegrees / 5 );
  1105. pointCount = pointCount < 2 ? 2 : pointCount;
  1106. // alternative to this hardcoded version: https://stackoverflow.com/a/18499923/2179399
  1107. }
  1108. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  1109. const pLine = curve.tryGetPolyline();
  1110. for ( let i = 0; i < pLine.count; i ++ ) {
  1111. rc.push( pLine.get( i ) );
  1112. }
  1113. pLine.delete();
  1114. return rc;
  1115. }
  1116. const domain = curve.domain;
  1117. const divisions = pointCount - 1.0;
  1118. for ( let j = 0; j < pointCount; j ++ ) {
  1119. const t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  1120. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  1121. ts.push( t );
  1122. continue;
  1123. }
  1124. const tan = curve.tangentAt( t );
  1125. const prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  1126. // Duplicated from THREE.Vector3
  1127. // How to pass imports to worker?
  1128. const tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  1129. const ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  1130. const denominator = Math.sqrt( tS * ptS );
  1131. let angle;
  1132. if ( denominator === 0 ) {
  1133. angle = Math.PI / 2;
  1134. } else {
  1135. const theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  1136. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  1137. }
  1138. if ( angle < 0.1 ) continue;
  1139. ts.push( t );
  1140. }
  1141. rc = ts.map( t => curve.pointAt( t ) );
  1142. return rc;
  1143. }
  1144. }
  1145. export { Rhino3dmLoader };
粤ICP备19079148号