3DMLoader.js 27 KB

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