3DMLoader.js 23 KB

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