3DMLoader.js 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. import {
  2. BufferGeometryLoader,
  3. FileLoader,
  4. Loader,
  5. Object3D,
  6. MeshStandardMaterial,
  7. Mesh,
  8. Color,
  9. Points,
  10. PointsMaterial,
  11. Line,
  12. LineBasicMaterial,
  13. Matrix4,
  14. DirectionalLight,
  15. PointLight,
  16. SpotLight,
  17. RectAreaLight,
  18. Vector3,
  19. Sprite,
  20. SpriteMaterial,
  21. CanvasTexture,
  22. LinearFilter,
  23. ClampToEdgeWrapping
  24. } from "../../../build/three.module.js";
  25. var Rhino3dmLoader = function ( manager ) {
  26. Loader.call( this, manager );
  27. this.libraryPath = '';
  28. this.libraryPending = null;
  29. this.libraryBinary = null;
  30. this.libraryConfig = {};
  31. this.workerLimit = 4;
  32. this.workerPool = [];
  33. this.workerNextTaskID = 1;
  34. this.workerSourceURL = '';
  35. this.workerConfig = {};
  36. this.materials = [];
  37. };
  38. Rhino3dmLoader.taskCache = new WeakMap();
  39. Rhino3dmLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  40. constructor: Rhino3dmLoader,
  41. setLibraryPath: function ( path ) {
  42. this.libraryPath = path;
  43. return this;
  44. },
  45. setWorkerLimit: function ( workerLimit ) {
  46. this.workerLimit = workerLimit;
  47. return this;
  48. },
  49. load: function ( url, onLoad, onProgress, onError ) {
  50. var loader = new FileLoader( this.manager );
  51. loader.setPath( this.path );
  52. loader.setResponseType( 'arraybuffer' );
  53. loader.setRequestHeader( this.requestHeader );
  54. loader.load( url, ( buffer ) => {
  55. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  56. // again from this thread.
  57. if ( Rhino3dmLoader.taskCache.has( buffer ) ) {
  58. var cachedTask = Rhino3dmLoader.taskCache.get( buffer );
  59. return cachedTask.promise.then( onLoad ).catch( onError );
  60. }
  61. this.decodeObjects( buffer, url )
  62. .then( onLoad )
  63. .catch( onError );
  64. }, onProgress, onError );
  65. },
  66. debug: function () {
  67. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  68. },
  69. decodeObjects: function ( buffer, url ) {
  70. var worker;
  71. var taskID;
  72. var taskCost = buffer.byteLength;
  73. var objectPending = this._getWorker( taskCost )
  74. .then( ( _worker ) => {
  75. worker = _worker;
  76. taskID = this.workerNextTaskID ++; //hmmm
  77. return new Promise( ( resolve, reject ) => {
  78. worker._callbacks[ taskID ] = { resolve, reject };
  79. worker.postMessage( { type: 'decode', id: taskID, buffer }, [ buffer ] );
  80. //this.debug();
  81. } );
  82. } )
  83. .then( ( message ) => this._createGeometry( message.data ) );
  84. // Remove task from the task list.
  85. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  86. objectPending
  87. .catch( () => true )
  88. .then( () => {
  89. if ( worker && taskID ) {
  90. this._releaseTask( worker, taskID );
  91. //this.debug();
  92. }
  93. } );
  94. // Cache the task result.
  95. Rhino3dmLoader.taskCache.set( buffer, {
  96. url: url,
  97. promise: objectPending
  98. } );
  99. return objectPending;
  100. },
  101. parse: function ( data, onLoad, onError ) {
  102. this.decodeObjects( data, '' )
  103. .then( onLoad )
  104. .catch( onError );
  105. },
  106. _compareMaterials: function ( material ) {
  107. var mat = {};
  108. mat.name = material.name;
  109. mat.color = {};
  110. mat.color.r = material.color.r;
  111. mat.color.g = material.color.g;
  112. mat.color.b = material.color.b;
  113. mat.type = material.type;
  114. for ( var i = 0; i < this.materials.length; i ++ ) {
  115. var m = this.materials[ i ];
  116. var _mat = {};
  117. _mat.name = m.name;
  118. _mat.color = {};
  119. _mat.color.r = m.color.r;
  120. _mat.color.g = m.color.g;
  121. _mat.color.b = m.color.b;
  122. _mat.type = m.type;
  123. if ( JSON.stringify( mat ) === JSON.stringify( _mat ) ) {
  124. return m;
  125. }
  126. }
  127. this.materials.push( material );
  128. return material;
  129. },
  130. _createMaterial: function ( material ) {
  131. if ( material === undefined ) {
  132. return new MeshStandardMaterial( {
  133. color: new Color( 1, 1, 1 ),
  134. metalness: 0.8,
  135. name: 'default',
  136. side: 2
  137. } );
  138. }
  139. var _diffuseColor = material.diffuseColor;
  140. var diffusecolor = new Color( _diffuseColor.r / 255.0, _diffuseColor.g / 255.0, _diffuseColor.b / 255.0 );
  141. if ( _diffuseColor.r === 0 && _diffuseColor.g === 0 && _diffuseColor.b === 0 ) {
  142. diffusecolor.r = 1;
  143. diffusecolor.g = 1;
  144. diffusecolor.b = 1;
  145. }
  146. return new MeshStandardMaterial( {
  147. color: diffusecolor,
  148. metalness: 0.8,
  149. name: material.name,
  150. side: 2
  151. } );
  152. },
  153. _createGeometry: function ( data ) {
  154. // console.log(data);
  155. var object = new Object3D();
  156. var instanceDefinitionObjects = [];
  157. var instanceDefinitions = [];
  158. var instanceReferences = [];
  159. object.userData[ 'layers' ] = data.layers;
  160. object.userData[ 'groups' ] = data.groups;
  161. var objects = data.objects;
  162. var materials = data.materials;
  163. for ( var i = 0; i < objects.length; i ++ ) {
  164. var obj = objects[ i ];
  165. var attributes = obj.attributes;
  166. switch ( obj.objectType ) {
  167. case 'InstanceDefinition':
  168. instanceDefinitions.push( obj );
  169. break;
  170. case 'InstanceReference':
  171. instanceReferences.push( obj );
  172. break;
  173. default:
  174. var material = this._createMaterial( materials[ attributes.materialIndex ] );
  175. material = this._compareMaterials( material );
  176. var _object = this._createObject( obj, material );
  177. if ( _object === undefined ) {
  178. continue;
  179. }
  180. _object.visible = data.layers[ attributes.layerIndex ].visible;
  181. if ( attributes.isInstanceDefinitionObject ) {
  182. instanceDefinitionObjects.push( _object );
  183. } else {
  184. object.add( _object );
  185. }
  186. break;
  187. }
  188. }
  189. for ( var i = 0; i < instanceDefinitions.length; i ++ ) {
  190. var iDef = instanceDefinitions[ i ];
  191. var objects = [];
  192. for ( var j = 0; j < iDef.attributes.objectIds.length; j ++ ) {
  193. var objId = iDef.attributes.objectIds[ j ];
  194. for ( var p = 0; p < instanceDefinitionObjects.length; p ++ ) {
  195. var idoId = instanceDefinitionObjects[ p ].userData.attributes.id;
  196. if ( objId === idoId ) {
  197. objects.push( instanceDefinitionObjects[ p ] );
  198. }
  199. }
  200. }
  201. // Currently clones geometry and does not take advantage of instancing
  202. for ( var j = 0; j < instanceReferences.length; j ++ ) {
  203. var iRef = instanceReferences[ j ];
  204. if ( iRef.geometry.parentIdefId === iDef.attributes.id ) {
  205. var iRefObject = new Object3D();
  206. var xf = iRef.geometry.xform.array;
  207. var matrix = new Matrix4();
  208. matrix.set( xf[ 0 ], xf[ 1 ], xf[ 2 ], xf[ 3 ], xf[ 4 ], xf[ 5 ], xf[ 6 ], xf[ 7 ], xf[ 8 ], xf[ 9 ], xf[ 10 ], xf[ 11 ], xf[ 12 ], xf[ 13 ], xf[ 14 ], xf[ 15 ] );
  209. iRefObject.applyMatrix4( matrix );
  210. for ( var p = 0; p < objects.length; p ++ ) {
  211. iRefObject.add( objects[ p ].clone( true ) );
  212. }
  213. object.add( iRefObject );
  214. }
  215. }
  216. }
  217. this.materials = [];
  218. return object;
  219. },
  220. _createObject: function ( obj, mat ) {
  221. var loader = new BufferGeometryLoader();
  222. var attributes = obj.attributes;
  223. switch ( obj.objectType ) {
  224. case 'Point':
  225. case 'PointSet':
  226. var geometry = loader.parse( obj.geometry );
  227. var material = new PointsMaterial( { sizeAttenuation: true, vertexColors: true } );
  228. material = this._compareMaterials( material );
  229. var points = new Points( geometry, material );
  230. points.userData[ 'attributes' ] = attributes;
  231. points.userData[ 'objectType' ] = obj.objectType;
  232. return points;
  233. case 'Mesh':
  234. case 'Extrusion':
  235. var geometry = loader.parse( obj.geometry );
  236. if ( geometry.attributes.hasOwnProperty( 'color' ) ) {
  237. mat.vertexColors = true;
  238. }
  239. var mesh = new Mesh( geometry, mat );
  240. mesh.castShadow = attributes.castsShadows;
  241. mesh.receiveShadow = attributes.receivesShadows;
  242. mesh.userData[ 'attributes' ] = attributes;
  243. mesh.userData[ 'objectType' ] = obj.objectType;
  244. return mesh;
  245. case 'Brep':
  246. var brepObject = new Object3D();
  247. for ( var j = 0; j < obj.geometry.length; j ++ ) {
  248. geometry = loader.parse( obj.geometry[ j ] );
  249. var mesh = new Mesh( geometry, mat );
  250. mesh.castShadow = attributes.castsShadows;
  251. mesh.receiveShadow = attributes.receivesShadows;
  252. brepObject.add( mesh );
  253. }
  254. brepObject.userData[ 'attributes' ] = attributes;
  255. brepObject.userData[ 'objectType' ] = obj.objectType;
  256. return brepObject;
  257. case 'Curve':
  258. geometry = loader.parse( obj.geometry );
  259. var _color = attributes.drawColor;
  260. var color = new Color( _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 );
  261. var material = new LineBasicMaterial( { color: color } );
  262. material = this._compareMaterials( material );
  263. var lines = new Line( geometry, material );
  264. lines.userData[ 'attributes' ] = attributes;
  265. lines.userData[ 'objectType' ] = obj.objectType;
  266. return lines;
  267. case 'TextDot':
  268. geometry = obj.geometry;
  269. var ctx = document.createElement( 'canvas' ).getContext( '2d' );
  270. var font = `${geometry.fontHeight}px ${geometry.fontFace}`;
  271. ctx.font = font;
  272. var width = ctx.measureText( geometry.text ).width + 10;
  273. var height = geometry.fontHeight + 10;
  274. ctx.canvas.width = width;
  275. ctx.canvas.height = height;
  276. ctx.font = font;
  277. ctx.textBaseline = 'middle';
  278. ctx.textAlign = 'center';
  279. var color = attributes.drawColor;
  280. ctx.fillStyle = `rgba(${color.r},${color.g},${color.b},${color.a})`;
  281. ctx.fillRect( 0, 0, width, height );
  282. ctx.fillStyle = 'white';
  283. ctx.fillText( geometry.text, width / 2, height / 2 );
  284. var texture = new CanvasTexture( ctx.canvas );
  285. texture.minFilter = LinearFilter;
  286. texture.wrapS = ClampToEdgeWrapping;
  287. texture.wrapT = ClampToEdgeWrapping;
  288. var material = new SpriteMaterial( { map: texture, depthTest: false } );
  289. var sprite = new Sprite( material );
  290. sprite.position.set( geometry.point[ 0 ], geometry.point[ 1 ], geometry.point[ 2 ] );
  291. sprite.scale.set( width / 10, height / 10, 1.0 );
  292. sprite.userData[ 'attributes' ] = attributes;
  293. sprite.userData[ 'objectType' ] = obj.objectType;
  294. return sprite;
  295. case 'Light':
  296. geometry = obj.geometry;
  297. var light;
  298. if ( geometry.isDirectionalLight ) {
  299. light = new DirectionalLight();
  300. light.castShadow = attributes.castsShadows;
  301. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  302. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  303. light.shadow.normalBias = 0.1;
  304. } else if ( geometry.isPointLight ) {
  305. light = new PointLight();
  306. light.castShadow = attributes.castsShadows;
  307. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  308. light.shadow.normalBias = 0.1;
  309. } else if ( geometry.isRectangularLight ) {
  310. light = new RectAreaLight();
  311. var width = Math.abs( geometry.width[ 2 ] );
  312. var height = Math.abs( geometry.length[ 0 ] );
  313. light.position.set( geometry.location[ 0 ] - ( height / 2 ), geometry.location[ 1 ], geometry.location[ 2 ] - ( width / 2 ) );
  314. light.height = height;
  315. light.width = width;
  316. light.lookAt( new Vector3( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] ) );
  317. } else if ( geometry.isSpotLight ) {
  318. light = new SpotLight();
  319. light.castShadow = attributes.castsShadows;
  320. light.position.set( geometry.location[ 0 ], geometry.location[ 1 ], geometry.location[ 2 ] );
  321. light.target.position.set( geometry.direction[ 0 ], geometry.direction[ 1 ], geometry.direction[ 2 ] );
  322. light.angle = geometry.spotAngleRadians;
  323. light.shadow.normalBias = 0.1;
  324. } else if ( geometry.isLinearLight ) {
  325. console.warn( `THREE.3DMLoader: No conversion exists for linear lights.` );
  326. return;
  327. }
  328. if ( light ) {
  329. light.intensity = geometry.intensity;
  330. light.userData[ 'attributes' ] = attributes;
  331. light.userData[ 'objectType' ] = obj.objectType;
  332. }
  333. return light;
  334. }
  335. },
  336. _initLibrary: function () {
  337. if ( ! this.libraryPending ) {
  338. // Load rhino3dm wrapper.
  339. var jsLoader = new FileLoader( this.manager );
  340. jsLoader.setPath( this.libraryPath );
  341. var jsContent = new Promise( ( resolve, reject ) => {
  342. jsLoader.load( 'rhino3dm.js', resolve, undefined, reject );
  343. } );
  344. // Load rhino3dm WASM binary.
  345. var binaryLoader = new FileLoader( this.manager );
  346. binaryLoader.setPath( this.libraryPath );
  347. binaryLoader.setResponseType( 'arraybuffer' );
  348. var binaryContent = new Promise( ( resolve, reject ) => {
  349. binaryLoader.load( 'rhino3dm.wasm', resolve, undefined, reject );
  350. } );
  351. this.libraryPending = Promise.all( [ jsContent, binaryContent ] )
  352. .then( ( [ jsContent, binaryContent ] ) => {
  353. //this.libraryBinary = binaryContent;
  354. this.libraryConfig.wasmBinary = binaryContent;
  355. var fn = Rhino3dmLoader.Rhino3dmWorker.toString();
  356. var body = [
  357. '/* rhino3dm.js */',
  358. jsContent,
  359. '/* worker */',
  360. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  361. ].join( '\n' );
  362. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  363. } );
  364. }
  365. return this.libraryPending;
  366. },
  367. _getWorker: function ( taskCost ) {
  368. return this._initLibrary().then( () => {
  369. if ( this.workerPool.length < this.workerLimit ) {
  370. var worker = new Worker( this.workerSourceURL );
  371. worker._callbacks = {};
  372. worker._taskCosts = {};
  373. worker._taskLoad = 0;
  374. worker.postMessage( {
  375. type: 'init',
  376. libraryConfig: this.libraryConfig
  377. } );
  378. worker.onmessage = function ( e ) {
  379. var message = e.data;
  380. switch ( message.type ) {
  381. case 'decode':
  382. worker._callbacks[ message.id ].resolve( message );
  383. break;
  384. case 'error':
  385. worker._callbacks[ message.id ].reject( message );
  386. break;
  387. default:
  388. console.error( 'THREE.Rhino3dmLoader: Unexpected message, "' + message.type + '"' );
  389. }
  390. };
  391. this.workerPool.push( worker );
  392. } else {
  393. this.workerPool.sort( function ( a, b ) {
  394. return a._taskLoad > b._taskLoad ? - 1 : 1;
  395. } );
  396. }
  397. var worker = this.workerPool[ this.workerPool.length - 1 ];
  398. worker._taskLoad += taskCost;
  399. return worker;
  400. } );
  401. },
  402. _releaseTask: function ( worker, taskID ) {
  403. worker._taskLoad -= worker._taskCosts[ taskID ];
  404. delete worker._callbacks[ taskID ];
  405. delete worker._taskCosts[ taskID ];
  406. },
  407. dispose: function () {
  408. for ( var i = 0; i < this.workerPool.length; ++ i ) {
  409. this.workerPool[ i ].terminate();
  410. }
  411. this.workerPool.length = 0;
  412. return this;
  413. }
  414. } );
  415. /* WEB WORKER */
  416. Rhino3dmLoader.Rhino3dmWorker = function () {
  417. var libraryPending;
  418. var libraryConfig;
  419. var rhino;
  420. onmessage = function ( e ) {
  421. var message = e.data;
  422. switch ( message.type ) {
  423. case 'init':
  424. libraryConfig = message.libraryConfig;
  425. var wasmBinary = libraryConfig.wasmBinary;
  426. var RhinoModule;
  427. libraryPending = new Promise( function ( resolve ) {
  428. /* Like Basis Loader */
  429. RhinoModule = { wasmBinary, onRuntimeInitialized: resolve };
  430. rhino3dm( RhinoModule );
  431. } ).then( () => {
  432. rhino = RhinoModule;
  433. } );
  434. break;
  435. case 'decode':
  436. var buffer = message.buffer;
  437. libraryPending.then( () => {
  438. var data = decodeObjects( rhino, buffer );
  439. self.postMessage( { type: 'decode', id: message.id, data } );
  440. } );
  441. break;
  442. }
  443. };
  444. function decodeObjects( rhino, buffer ) {
  445. var arr = new Uint8Array( buffer );
  446. var doc = rhino.File3dm.fromByteArray( arr );
  447. var objects = [];
  448. var materials = [];
  449. var layers = [];
  450. var views = [];
  451. var namedViews = [];
  452. var groups = [];
  453. //Handle objects
  454. for ( var i = 0; i < doc.objects().count; i ++ ) {
  455. var _object = doc.objects().get( i );
  456. var object = extractObjectData( _object, doc );
  457. if ( object !== undefined ) {
  458. objects.push( object );
  459. }
  460. _object.delete();
  461. }
  462. // Handle instance definitions
  463. for ( var i = 0; i < doc.instanceDefinitions().count(); i ++ ) {
  464. var idef = doc.instanceDefinitions().get( i );
  465. var idefAttributes = extractProperties( idef );
  466. idefAttributes.objectIds = idef.getObjectIds();
  467. objects.push( { geometry: null, attributes: idefAttributes, objectType: 'InstanceDefinition' } );
  468. }
  469. // Handle materials
  470. for ( var i = 0; i < doc.materials().count(); i ++ ) {
  471. var _material = doc.materials().get( i );
  472. var materialProperties = extractProperties( _material );
  473. var pbMaterialProperties = extractProperties( _material.physicallyBased() );
  474. var material = Object.assign( materialProperties, pbMaterialProperties );
  475. materials.push( material );
  476. _material.delete();
  477. }
  478. // Handle layers
  479. for ( var i = 0; i < doc.layers().count(); i ++ ) {
  480. var _layer = doc.layers().get( i );
  481. var layer = extractProperties( _layer );
  482. layers.push( layer );
  483. _layer.delete();
  484. }
  485. // Handle views
  486. for ( var i = 0; i < doc.views().count(); i ++ ) {
  487. var _view = doc.views().get( i );
  488. var view = extractProperties( _view );
  489. views.push( view );
  490. _view.delete();
  491. }
  492. // Handle named views
  493. for ( var i = 0; i < doc.namedViews().count(); i ++ ) {
  494. var _namedView = doc.namedViews().get( i );
  495. var namedView = extractProperties( _namedView );
  496. namedViews.push( namedView );
  497. _namedView.delete();
  498. }
  499. // Handle groups
  500. for ( var i = 0; i < doc.groups().count(); i ++ ) {
  501. var _group = doc.groups().get( i );
  502. var group = extractProperties( _group );
  503. groups.push( group );
  504. _group.delete();
  505. }
  506. // Handle settings
  507. var settings = extractProperties( doc.settings() );
  508. //TODO: Handle other document stuff like dimstyles, instance definitions, bitmaps etc.
  509. // Handle dimstyles
  510. // console.log(`Dimstyle Count: ${doc.dimstyles().count()}`);
  511. // Handle bitmaps
  512. // console.log(`Bitmap Count: ${doc.bitmaps().count()}`);
  513. // Handle instance definitions
  514. // console.log(`Instance Definitions Count: ${doc.instanceDefinitions().count()}`);
  515. // Handle strings -- this seems to be broken at the moment in rhino3dm
  516. // console.log(`Strings Count: ${doc.strings().count()}`);
  517. /*
  518. for( var i = 0; i < doc.strings().count(); i++ ){
  519. var _string= doc.strings().get( i );
  520. console.log(_string);
  521. var string = extractProperties( _group );
  522. strings.push( string );
  523. _string.delete();
  524. }
  525. */
  526. doc.delete();
  527. return { objects, materials, layers, views, namedViews, groups, settings };
  528. }
  529. function extractObjectData( object, doc ) {
  530. var _geometry = object.geometry();
  531. var _attributes = object.attributes();
  532. var objectType = _geometry.objectType;
  533. var geometry = null;
  534. var attributes = null;
  535. // skip instance definition objects
  536. //if( _attributes.isInstanceDefinitionObject ) { continue; }
  537. // TODO: handle other geometry types
  538. switch ( objectType ) {
  539. case rhino.ObjectType.Curve:
  540. var pts = curveToPoints( _geometry, 100 );
  541. var position = {};
  542. var color = {};
  543. var attributes = {};
  544. var data = {};
  545. position.itemSize = 3;
  546. position.type = 'Float32Array';
  547. position.array = [];
  548. for ( var j = 0; j < pts.length; j ++ ) {
  549. position.array.push( pts[ j ][ 0 ] );
  550. position.array.push( pts[ j ][ 1 ] );
  551. position.array.push( pts[ j ][ 2 ] );
  552. }
  553. attributes.position = position;
  554. data.attributes = attributes;
  555. geometry = { data };
  556. break;
  557. case rhino.ObjectType.Point:
  558. var pt = _geometry.location;
  559. var position = {};
  560. var color = {};
  561. var attributes = {};
  562. var data = {};
  563. position.itemSize = 3;
  564. position.type = 'Float32Array';
  565. position.array = [ pt[ 0 ], pt[ 1 ], pt[ 2 ] ];
  566. var _color = _attributes.drawColor( doc );
  567. color.itemSize = 3;
  568. color.type = 'Float32Array';
  569. color.array = [ _color.r / 255.0, _color.g / 255.0, _color.b / 255.0 ];
  570. attributes.position = position;
  571. attributes.color = color;
  572. data.attributes = attributes;
  573. geometry = { data };
  574. break;
  575. case rhino.ObjectType.PointSet:
  576. case rhino.ObjectType.Mesh:
  577. geometry = _geometry.toThreejsJSON();
  578. break;
  579. case rhino.ObjectType.Brep:
  580. var faces = _geometry.faces();
  581. geometry = [];
  582. for ( var faceIndex = 0; faceIndex < faces.count; faceIndex ++ ) {
  583. var face = faces.get( faceIndex );
  584. var mesh = face.getMesh( rhino.MeshType.Any );
  585. if ( mesh ) {
  586. geometry.push( mesh.toThreejsJSON() );
  587. mesh.delete();
  588. }
  589. face.delete();
  590. }
  591. faces.delete();
  592. break;
  593. case rhino.ObjectType.Extrusion:
  594. var mesh = _geometry.getMesh( rhino.MeshType.Any );
  595. if ( mesh ) {
  596. geometry = mesh.toThreejsJSON();
  597. mesh.delete();
  598. }
  599. break;
  600. case rhino.ObjectType.TextDot:
  601. geometry = extractProperties( _geometry );
  602. break;
  603. case rhino.ObjectType.Light:
  604. geometry = extractProperties( _geometry );
  605. break;
  606. case rhino.ObjectType.InstanceReference:
  607. geometry = extractProperties( _geometry );
  608. geometry.xform = extractProperties( _geometry.xform );
  609. geometry.xform.array = _geometry.xform.toFloatArray( true );
  610. break;
  611. /*
  612. case rhino.ObjectType.Annotation:
  613. case rhino.ObjectType.Hatch:
  614. case rhino.ObjectType.SubD:
  615. case rhino.ObjectType.ClipPlane:
  616. */
  617. default:
  618. console.warn( `THREE.3DMLoader: TODO: Implement ${objectType.constructor.name}` );
  619. break;
  620. }
  621. if ( geometry ) {
  622. var attributes = extractProperties( _attributes );
  623. if ( _attributes.groupCount > 0 ) {
  624. attributes.groupIds = _attributes.getGroupList();
  625. }
  626. attributes.drawColor = _attributes.drawColor( doc );
  627. objectType = objectType.constructor.name;
  628. objectType = objectType.substring( 11, objectType.length );
  629. return { geometry, attributes, objectType };
  630. }
  631. }
  632. function extractProperties( object ) {
  633. var result = {};
  634. for ( var property in object ) {
  635. if ( typeof object[ property ] !== 'function' ) {
  636. result[ property ] = object[ property ];
  637. } else {
  638. // console.log(`${property}: ${object[property]}`);
  639. }
  640. }
  641. return result;
  642. }
  643. function curveToPoints( curve, pointLimit ) {
  644. var pointCount = pointLimit;
  645. var rc = [];
  646. var ts = [];
  647. if ( curve instanceof rhino.LineCurve ) {
  648. return [ curve.pointAtStart, curve.pointAtEnd ];
  649. }
  650. if ( curve instanceof rhino.PolylineCurve ) {
  651. pointCount = curve.pointCount;
  652. for ( var i = 0; i < pointCount; i ++ ) {
  653. rc.push( curve.point( i ) );
  654. }
  655. return rc;
  656. }
  657. if ( curve instanceof rhino.PolyCurve ) {
  658. var segmentCount = curve.segmentCount;
  659. for ( var i = 0; i < segmentCount; i ++ ) {
  660. var segment = curve.segmentCurve( i );
  661. var segmentArray = curveToPoints( segment );
  662. rc = rc.concat( segmentArray );
  663. segment.delete();
  664. }
  665. return rc;
  666. }
  667. if ( curve instanceof rhino.NurbsCurve && curve.degree === 1 ) {
  668. // console.info( 'degree 1 curve' );
  669. }
  670. var domain = curve.domain;
  671. var divisions = pointCount - 1.0;
  672. for ( var j = 0; j < pointCount; j ++ ) {
  673. var t = domain[ 0 ] + ( j / divisions ) * ( domain[ 1 ] - domain[ 0 ] );
  674. if ( t === domain[ 0 ] || t === domain[ 1 ] ) {
  675. ts.push( t );
  676. continue;
  677. }
  678. var tan = curve.tangentAt( t );
  679. var prevTan = curve.tangentAt( ts.slice( - 1 )[ 0 ] );
  680. // Duplicaated from THREE.Vector3
  681. // How to pass imports to worker?
  682. var tS = tan[ 0 ] * tan[ 0 ] + tan[ 1 ] * tan[ 1 ] + tan[ 2 ] * tan[ 2 ];
  683. var ptS = prevTan[ 0 ] * prevTan[ 0 ] + prevTan[ 1 ] * prevTan[ 1 ] + prevTan[ 2 ] * prevTan[ 2 ];
  684. var denominator = Math.sqrt( tS * ptS );
  685. var angle;
  686. if ( denominator === 0 ) {
  687. angle = Math.PI / 2;
  688. } else {
  689. var theta = ( tan.x * prevTan.x + tan.y * prevTan.y + tan.z * prevTan.z ) / denominator;
  690. angle = Math.acos( Math.max( - 1, Math.min( 1, theta ) ) );
  691. }
  692. if ( angle < 0.1 ) continue;
  693. ts.push( t );
  694. }
  695. rc = ts.map( t => curve.pointAt( t ) );
  696. return rc;
  697. }
  698. };
  699. export { Rhino3dmLoader };