3DMLoader.js 28 KB

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