3DMLoader.js 29 KB

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